除了 ConnectionError 或 TimeoutError 不工作

except ConnectionError or TimeoutError not working

如果出现连接错误,我希望 Python 等待并重试。这是相关代码,其中 "link" 是一些 link:

import requests
import urllib.request
import urllib.parse

from random import randint

try:
    r=requests.get(link)

except ConnectionError or TimeoutError:
    print("Will retry again in a little bit")
    time.sleep(randint(2500,3000))
    r=requests.get(link)

除了我仍然定期收到连接错误。而且我从来没有看到文本 "Will retry again in a little bit" 所以我知道代码没有重试。我究竟做错了什么?我在下面粘贴了部分错误代码,以防我误读错误。 TIA!

TimeoutError: [WinError 10060]连接尝试失败,因为连接方在一段时间后没有正确响应,或者建立连接失败,因为连接的主机没有响应

在处理上述异常的过程中,又发生了一个异常:

requests.packages.urllib3.exceptions.ProtocolError: ('Connection aborted.', TimeoutError(10060, 'A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond', None, 10060, None))

在处理上述异常的过程中,又发生了一个异常:

requests.exceptions.ConnectionError: ('Connection aborted.', TimeoutError(10060, 'A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond', None, 10060, None))

我认为你应该使用

except (ConnectionError, TimeoutError) as e:
    print("Will retry again in a little bit")
    time.sleep(randint(2500,3000))
    r=requests.get(link)

this similar question, or check the docs

第二个请求不在 try 块内,因此未捕获到异常。同样在 try-except 块中,您没有捕捉到可能发生的其他异常。
您可以使用循环尝试连接两次,如果请求成功则中断。

for _ in range(2):
    try:
        r = requests.get(link)
        break
    except (ConnectionError, TimeoutError):
        print("Will retry again in a little bit")
    except Exception as e:
        print(e)
    time.sleep(randint(2500,3000))

对我来说,在请求中使用自定义用户代理可以解决这个问题。使用此方法,您可以欺骗浏览器。

作品:

url = "https://www.nasdaq.com/market-activity/stocks/amd"
headers = {'User-Agent': 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.6) Gecko/20070802 SeaMonkey/1.1.4'}
response = requests.get(url, headers=headers)

无效:

url = "https://www.nasdaq.com/market-activity/stocks/amd"
response = requests.get(url)

我遇到了同样的问题。事实证明,urlib3 依赖于 socket.py,这会引发 OSError。所以,你需要明白这一点:

try:
    r = requests.get(link)
except OSError as e:
    print("There as an error: {}".format(e))