我正在尝试使用代理连接到站点:
import requests
import socket
# ...
def getLink(proxy, userAgent, link):
try:
# ...
proxies = {'http': proxy}
headers = {'User-Agent': userAgent}
r = requests.get(link, headers=headers, proxies=proxies, timeout=10)
# ...
except (socket.timeout, requests.exceptions.TimeoutException, RequestException, socket.error):
print('Timeout error! Retrying...')
return 0
使用错误的代理运行此代码,在10秒钟内出现此错误:
Traceback (most recent call last):
File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\urllib3\connection.py", line 159, in _new_conn
(self._dns_host, self.port), self.timeout, **extra_kw)
File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\urllib3\util\connection.py", line 80, in create_connection
raise err
File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\urllib3\util\connection.py", line 70, in create_connection
sock.connect(sa)
socket.timeout: timed out
During handling of the above exception, another exception occurred:
...
在github上,我读到这是一个urllib库错误,并且在处理方面存在问题。如何在 try 构造中处理它?</ p>