标签: python-requests

从requests.exceptions.HTTPError获取HTTP错误代码

我抓住这样的例外,

def get_url_fp(image_url, request_kwargs=None):
    response = requests.get(some_url, **request_kwargs)
    response.raise_for_status()
    return response.raw


try:
   a = "http://example.com"
   fp = get_url_fp(a)

except HTTPError as e:
    # Need to check its an 404, 503, 500, 403 etc.
Run Code Online (Sandbox Code Playgroud)

python exception http python-requests

36
推荐指数
2
解决办法
3万
查看次数

从Flask返回一个requests.Response对象

我正在尝试使用Flask和请求构建一个简单的代理.代码如下:

@app.route('/es/<string:index>/<string:type>/<string:id>',
           methods=['GET', 'POST', 'PUT']):
def es(index, type, id):
    elasticsearch = find_out_where_elasticsearch_lives()
    # also handle some authentication
    url = '%s%s%s%s' % (elasticsearch, index, type, id)

    esreq = requests.Request(method=request.method, url=url,
                             headers=request.headers, data=request.data)
    resp = requests.Session().send(esreq.prepare())
    return resp.text
Run Code Online (Sandbox Code Playgroud)

这有效,除了它丢失了Elasticsearch的状态代码.我尝试直接返回resp(a requests.models.Response),但这失败了

TypeError: 'Response' object is not callable
Run Code Online (Sandbox Code Playgroud)

还有另一种简单的方法可以requests.models.Response从烧瓶中返回吗?

python proxy flask python-requests

36
推荐指数
2
解决办法
4万
查看次数

python请求ssl握手失败

每次我尝试做:

requests.get('https://url') 
Run Code Online (Sandbox Code Playgroud)

我收到了这条消息:

import requests
>>> requests.get('https://reviews.gethuman.com/companies') 
Traceback (most recent call last): 
   File "<stdin>", line 1, in <module> 
   File "/usr/lib/python2.7/dist-packages/requests/api.py", line 55, in get 
    return request('get', url, **kwargs) 
   File "/usr/lib/python2.7/dist-packages/requests/api.py", line 44, in request 
    return session.request(method=method, url=url, **kwargs)    
   File "/usr/lib/python2.7/dist-packages/requests/sessions.py", line 455, in request 
    resp = self.send(prep, **send_kwargs) 
   File "/usr/lib/python2.7/dist-packages/requests/sessions.py", line 558, in send 
    r = adapter.send(request, **kwargs) 
   File "/usr/lib/python2.7/dist-packages/requests/adapters.py", line 385, in send 
    raise SSLError(e) requests.exceptions.SSLError: [Errno 1]
_ssl.c:510: error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure
Run Code Online (Sandbox Code Playgroud)

我尝试了一切:

  • 更新我的请求
  • 更新我的ssl

但没有变化.

我使用的是Python …

python python-requests

36
推荐指数
4
解决办法
6万
查看次数

使用python请求下载CSV

这是我的代码:

import csv
import requests
with requests.Session() as s:
    s.post(url, data=payload)
    download = s.get('url that directly download a csv report')
Run Code Online (Sandbox Code Playgroud)

这使我可以访问csv文件.我尝试了不同的方法来处理下载:

这将在一个字符串中提供csv文件:

print download.content
Run Code Online (Sandbox Code Playgroud)

这将打印第一行并返回错误:_csv.Error:在未加引号的字段中看到的换行符

cr = csv.reader(download, dialect=csv.excel_tab)
for row in cr:
    print row
Run Code Online (Sandbox Code Playgroud)

这将在每一行中打印一个字母,它不会打印整个内容:

cr = csv.reader(download.content, dialect=csv.excel_tab)
for row in cr:
    print row
Run Code Online (Sandbox Code Playgroud)

我的问题是在这种情况下读取csv文件的最有效方法是什么.以及如何下载实际的csv文件.

谢谢

python csv python-requests

36
推荐指数
6
解决办法
6万
查看次数

为什么请求会引发此异常“check_hostname 需要 server_hostname”?

p={
    'http':'http://my correct proxy here',
    'https':'https://my correct proxy here'
    }
self.response=requests.get(url=url,headers=self.headers,timeout=(6,15),proxies=p)
Run Code Online (Sandbox Code Playgroud)

然后它引发异常:

Traceback (most recent call last):
  File "C:\Users\xyl13509876955\Desktop\Monitor\dicks.py", line 61, in send_request
    self.response=requests.get(url=url,headers=self.headers,timeout=(6,15),proxies=p)
  File "C:\Users\xyl13509876955\AppData\Local\Programs\Python\Python37\lib\site-packages\requests\api.py", line 76, in get
    return request('get', url, params=params, **kwargs)
  File "C:\Users\xyl13509876955\AppData\Local\Programs\Python\Python37\lib\site-packages\requests\api.py", line 61, in request
    return session.request(method=method, url=url, **kwargs)
  File "C:\Users\xyl13509876955\AppData\Local\Programs\Python\Python37\lib\site-packages\requests\sessions.py", line 542, in request
    resp = self.send(prep, **send_kwargs)
  File "C:\Users\xyl13509876955\AppData\Local\Programs\Python\Python37\lib\site-packages\requests\sessions.py", line 655, in send
    r = adapter.send(request, **kwargs)
  File "C:\Users\xyl13509876955\AppData\Local\Programs\Python\Python37\lib\site-packages\requests\adapters.py", line 449, in send
    timeout=timeout
  File "C:\Users\xyl13509876955\AppData\Local\Programs\Python\Python37\lib\site-packages\urllib3\connectionpool.py", line 696, in urlopen
    self._prepare_proxy(conn)
  File …
Run Code Online (Sandbox Code Playgroud)

python urllib3 python-requests

36
推荐指数
6
解决办法
5万
查看次数

请求(由SSLError引起(“由于SSL模块不可用,无法连接到HTTPS URL。”)PyCharm请求网站中的错误

通过Pycharm在Python3 Windows中使用请求,并收到SSL模块不可用错误

我花了几个小时试图弄清楚是什么原因造成的。我已经重新安装了Anaconda,并且完全卡住了。运行以下内容时

def Earlybird(daycount):
    url = 'https://msft.com'
    response = requests.get(url)
    print(response)
Earlybird()
Run Code Online (Sandbox Code Playgroud)

我收到错误

requests.exceptions.SSLError: HTTPSConnectionPool(host='msft.com', 
port=443): Max retries exceeded with url: / (Caused by SSLError("Can't 
connect to HTTPS URL because the SSL module is not available."))
Run Code Online (Sandbox Code Playgroud)

我不知道是什么原因造成的。由于Anaconda是最新安装的软件,因此我认为一切都是最新的,因此我不确定这是否指向错误的SSL吗?我对python有点陌生,因此感谢您的耐心配合。--

python ssl https pycharm python-requests

35
推荐指数
11
解决办法
4万
查看次数

Python请求异常处理

如何使用python库请求处理异常?例如,如何检查PC是否连接到互联网?

当我尝试

try:
    requests.get('http://www.google.com')
except ConnectionError:
    # handle the exception
Run Code Online (Sandbox Code Playgroud)

它给我的错误名称ConnectionError没有定义

python exception http-request python-requests

34
推荐指数
5
解决办法
5万
查看次数

Python:尝试使用请求POST表单

我正在尝试使用Python和请求库登录网站进行一些抓取,我正在尝试以下(这不起作用):

import requests
headers = {'User-Agent': 'Mozilla/5.0'}
payload = {'username':'niceusername','password':'123456'}

In [12]: r = requests.post('https://admin.example.com/login.php',headers=headers,data=payload)
Run Code Online (Sandbox Code Playgroud)

但是nada,重定向到登录页面.我需要开会吗?我做错了POST请求,是否需要加载cookie?会话会自动执行吗?我迷失在这里,需要一些帮助和解释.

我正在尝试登录的网站是php,我是否需要"捕获set-cookie并设置cookie标头"?如果是这样,我不知道该怎么做.该网页是一个包含以下内容的表单(如果有帮助):输入:用户名''密码''id':'myform','action':"login.php

一些额外的信息,也许你可以看到我在这里失踪的..

In [13]: r.headers
Out[13]: CaseInsensitiveDict({'content-encoding': 'gzip', 'transfer-encoding': 'chunked',
 'set-cookie': 'PHPSESSID=v233mnt4malhed55lrpc5bp8o1; path=/',
  'expires': 'Thu, 19 Nov 1981 08:52:00 GMT', 'vary': 'Accept-Encoding', 'server': 'nginx',
   'connection': 'keep-alive', 'pragma': 'no-cache',
    'cache-control': 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0',
     'date': 'Tue, 24 Dec 2013 10:50:44 GMT', 'content-type': 'text/html'})

In [14]: r.cookies
Out[14]: <<class 'requests.cookies.RequestsCookieJar'>[Cookie(version=0, name='PHPSESSID',
 value='v233mnt4malhed55lrpc5bp8o1', port=None, port_specified=False, domain='admin.example.com',
  domain_specified=False, domain_initial_dot=False, path='/', path_specified=True, secure=False,
   expires=None, discard=True, comment=None, comment_url=None, rest={}, …
Run Code Online (Sandbox Code Playgroud)

python python-requests

34
推荐指数
3
解决办法
9万
查看次数

如何在python请求库中实现重试机制?

我想为python请求库添加一个重试机制,因此使用它的脚本将重试非致命错误.

此刻我确实认为有些错误是可以恢复的:

  • HTTP返回码502,503,504
  • 主机未找到(现在不太重要)
  • 请求超时

在第一阶段,我确实想每分钟重试指定的5xx请求.

我希望能够透明地添加此功能,而无需为使用python-requests的这些脚本或库中的每个HTTP调用手动实现恢复.

python http python-requests

34
推荐指数
5
解决办法
2万
查看次数

使用Python请求:会话,Cookie和POST

我试图使用StubHub API来削减一些销售数据.这里看到的数据示例如下:

https://sell.stubhub.com/sellapi/event/4236070/section/null/seatmapdata

您会注意到,如果您尝试在不登录stubhub.com的情况下访问该URL,则无法使用.您需要先登录.

我通过网络浏览器登录后,打开要在新标签中抓取的URL,然后使用以下命令检索已删除的数据:

r = requests.get('https://sell.stubhub.com/sellapi/event/4236070/section/null/seatmapdata')
Run Code Online (Sandbox Code Playgroud)

但是,一旦浏览器会话在十分钟后过期,我会收到此错误:

<FormErrors>
<FormField>User Auth Check</FormField>
<ErrorMessage>
Either is not active or the session might have expired. Please login again.
</ErrorMessage>
Run Code Online (Sandbox Code Playgroud)

我认为我需要通过cookie实现会话ID,以保持我的身份验证活着.

对于之前从未做过这类事情的人来说,Requests库文档非常糟糕,所以我希望大家可以提供帮助.

请求提供的示例是:

s = requests.Session()

s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')
r = s.get("http://httpbin.org/cookies")

print r.text
# '{"cookies": {"sessioncookie": "123456789"}}'
Run Code Online (Sandbox Code Playgroud)

老实说,我无法做出正面或反面.如何在POST请求之间保留cookie?

python session-cookies python-3.x python-requests

33
推荐指数
1
解决办法
9万
查看次数