Requests报”requests.exceptions.ReadTimeout: {timeout message} “的原因以及解决办法

  • Post category:Python

这个异常”requests.exceptions.ReadTimeout”是Requests库中的异常之一, 表示请求超时导致无法获取返回的数据。例如,请求一个网站时,服务器响应时间过长或者网络连接不佳等情况都可能导致这个异常的发生。

常见的超时设置有两个参数,一个是连接超时(connect),即客户端建立连接到服务端响应之间的时间,另一个是服务器响应超时(read),即客户端连接上服务端之后等待服务端相应的时间。如果连接超时或者响应超时,Requests将会抛出超时异常。

针对这个异常,我们可以采取以下几种解决办法:

  1. 增加超时时间

增加或者调整超时时间来解决问题,可以在发送请求时添加timeout(连接超时时间和响应超时时间)参数来设置超时时间,默认情况下这个参数是None。例如,指定连接超时时间30s和响应超时时间60s:

import requests

url = 'http://www.example.com'
try:
    response = requests.get(url, timeout=(30, 60))
except requests.exceptions.Timeout as e:
    print('Timeout:', e)
  1. 配置代理

如果是因为网络不佳导致请求超时,可以尝试使用代理配置。需要注意的是,代理服务器的地址和端口不要使用默认值,否则可能会有别的网络问题影响请求。

import requests

proxies = {"http": "http://10.10.1.10:3128", "https": "https://10.10.1.11:1080"}

url = 'http://www.example.com'
try:
    response = requests.get(url, proxies=proxies, timeout=(30, 60))
except requests.exceptions.Timeout as e:
    print('Timeout:', e)

  1. 重试请求

当请求超时时,可以尝试重新发送请求。如果请求失败了,可以通过增加重试次数的方式解决问题。

如下代码,定义了一个请求次数,如果请求失败,则重新尝试。

import requests

url = 'http://www.example.com'
try:
    response = requests.get(url, timeout=(30, 60))
except requests.exceptions.Timeout as e:
    for i in range(3):
        try:
            response = requests.get(url, timeout=(30, 60))
            break
        except requests.exceptions.Timeout:
            if i == 2:
                print('Timeout:', e)

总之,解决Requests请求超时的问题需要具体情况具体分析,根据实际情况采取不同的解决办法。加强超时时间、配置代理、重试请求等方式都可以尝试。