Python Requests中异常总结

1. 连接超时

服务器在指定时间内没有应答,抛出 requests.exceptions.ConnectTimeout

requests.get('http://github.com', timeout=0.001)

# 抛出错误
requests.exceptions.ConnectTimeout: HTTPConnectionPool(host='github.com', port=80): Max retries exceeded with url: / (Caused by ConnectTimeoutError(<urllib3.connection.HTTPConnection object at 0x7f1b16da75f8>, 'Connection to github.com timed out. (connect timeout=0.001)'))

2. 连接、读取超时

若分别指定连接和读取的超时时间,服务器在指定时间没有应答,抛出 requests.exceptions.ConnectTimeout
- timeout=([连接超时时间], [读取超时时间])
- 连接:客户端连接服务器并并发送http请求服务器
- 读取:客户端等待服务器发送第一个字节之前的时间

requests.get('http://github.com', timeout=(6.05, 0.01))

# 抛出错误
requests.exceptions.ReadTimeout: HTTPConnectionPool(host='github.com', port=80): Read timed out. (read timeout=0.01)

3. 未知的服务器

抛出 requests.exceptions.ConnectionError


requests.get('http://github.comasf', timeout=(6.05, 27.05))

# 抛出错误
requests.exceptions.ConnectionError: HTTPConnectionPool(host='github.comasf', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f75826665f8>: Failed to establish a new connection: [Errno -2] Name or service not known',))

4. 代理连接不上

代理服务器拒绝建立连接,端口拒绝连接或未开放,抛出 requests.exceptions.ProxyError

requests.get('http://github.com', timeout=(6.05, 27.05), proxies={"http": "192.168.10.1:800"})

# 抛出错误
requests.exceptions.ProxyError: HTTPConnectionPool(host='192.168.10.1', port=800): Max retries exceeded with url: http://github.com/ (Caused by ProxyError('Cannot connect to proxy.', NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7fce3438c6d8>: Failed to establish a new connection: [Errno 111] Connection refused',)))

5. 连接代理超时

代理服务器没有响应 requests.exceptions.ConnectTimeout

requests.get('http://github.com', timeout=(6.05, 27.05), proxies={"http": "10.200.123.123:800"})

# 抛出错误
requests.exceptions.ConnectTimeout: HTTPConnectionPool(host='10.200.123.123', port=800): Max retries exceeded with url: http://github.com/ (Caused by ConnectTimeoutError(<urllib3.connection.HTTPConnection object at 0x7fa8896cc6d8>, 'Connection to 10.200.123.123 timed out. (connect timeout=6.05)'))

6. 代理读取超时

说明与代理建立连接成功,代理也发送请求到目标站点,但是代理读取目标站点资源超时
即使代理访问很快,如果代理服务器访问的目标站点超时,这个锅还是代理服务器背
假定代理可用,timeout就是向代理服务器的连接和读取过程的超时时间,不用关心代理服务器是否连接和读取成功

requests.get('http://github.com', timeout=(2, 0.01), proxies={"http": "192.168.10.1:800"})

# 抛出错误
requests.exceptions.ReadTimeout: HTTPConnectionPool(host='192.168.10.1:800', port=1080): Read timed out. (read timeout=0.5)

7. 网络环境异常

可能是断网导致,抛出 requests.exceptions.ConnectionError

requests.get('http://github.com', timeout=(6.05, 27.05))

# 抛出错误
requests.exceptions.ConnectionError: HTTPConnectionPool(host='github.com', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7fc8c17675f8>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution',))

8. 官网的一些参考

你可以告诉 requests 在经过以 timeout 参数设定的秒数时间之后停止等待响应。基本上所有的生产代码都应该使用这一参数。如果不使用,你的程序可能会永远失去响应:

>>> requests.get('http://github.com', timeout=0.001)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)

并不是整个下载响应的时间限制,而是如果服务器在 timeout 秒内没有应答,将会引发一个异常(更精确地说,是在 timeout 秒内没有从基础套接字上接收到任何字节的数据时)


- 遇到网络问题(如:DNS 查询失败、拒绝连接等)时,Requests 会抛出一个 requests.exceptions.ConnectionError 异常。
- 如果 HTTP 请求返回了不成功的状态码, Response.raise_for_status() 会抛出一个 HTTPError 异常。
- 若请求超时,则抛出一个 Timeout 异常。
- 若请求超过了设定的最大重定向次数,则会抛出一个 TooManyRedirects 异常。
- 所有Requests显式抛出的异常都继承自 requests.exceptions.RequestException
  • 24
    点赞
  • 90
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
### 回答1: 在使用 Pythonrequests 库进行请求时,如果返回的响应内容编码方式为 GBK,可以使用以下方法进行解码: ```python import requests resp = requests.get(url) resp.encoding = 'gbk' content = resp.text.encode('iso-8859-1').decode('gbk') ``` 其,`resp.encoding = 'gbk'` 指定了响应内容的编码方式为 GBK。但是,由于 requests 库默认使用的是 UTF-8 编码方式,因此需要将响应内容先转换成 ISO-8859-1 编码再进行解码。 另外,如果你经常需要处理 GBK 编码的内容,也可以考虑使用 chardet 库来自动识别编码方式,例如: ```python import requests import chardet resp = requests.get(url) encoding = chardet.detect(resp.content)['encoding'] content = resp.content.decode(encoding) ``` 这里使用了 chardet.detect 方法来自动识别响应内容的编码方式,然后再进行解码。 ### 回答2: Pythonrequests库是一个常用的HTTP客户端库,可以用于发送HTTP请求和获取HTTP响应。在处理HTTP响应时,requests库通常会根据响应的Content-Type自动进行解码。 对于Content-Type为text/html的响应,requests库会根据响应头的charset字段指定的编码格式进行解码。而对于某些网页,特别是文网页,它们的编码格式可能是gbk。如果不进行正确的解码,可能会导致显示乱码。 为了解决这个问题,我们可以通过设置requests库的encoding属性为'gbk',来指定解码编码。 例如: ``` import requests response = requests.get('http://example.com') # 发送GET请求 response.encoding = 'gbk' # 设置解码编码为gbk print(response.text) # 打印响应内容 ``` 上述代码会发送一个GET请求到'http://example.com',并将响应内容的解码编码设置为'gbk',最后打印响应内容。 这样做可以确保响应内容以gbk编码进行解码,从而正确显示文内容,避免出现乱码情况。 总结来说,Pythonrequests使用response.encoding = 'gbk'来对gbk编码进行解码,从而正确显示文内容。 ### 回答3: Pythonrequests库默认使用UTF-8编码,但当我们访问某些文网站时,可能会遇到GBK编码的页面。在使用requests库访问这样的网站时,我们可以通过指定响应的编码方式来进行GBK解码。 假设我们使用requests库发送一个GET请求并获取到响应,可以通过以下步骤进行GBK解码: 1. 首先,导入requests库:`import requests` 2. 然后,发送GET请求并获取响应:`response = requests.get(url)` 3. 接下来,设置响应的编码方式为GBK:`response.encoding = 'GBK'` 4. 最后,我们可以通过`response.text`来获取解码后的文本内容,即可处理文字符了。 下面是一个示例: ```python import requests url = 'http://example.com' response = requests.get(url) response.encoding = 'GBK' text = response.text print(text) ``` 以上代码会向'http://example.com'发送一个GET请求,并将响应的编码方式设置为GBK。然后,我们可以通过`response.text`获取解码后的文本内容,可以在输出结果看到正确显示的文字符。 通过以上步骤,我们就可以在使用requests库时正确解码文。当然,在实际应用,我们还可以根据需要进行异常处理,以确保程序的稳定性。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值