![](/img/trans.png)
[英]For loop web scraping a website brings up timeouterror, newconnectionerror and a requests.exceptions.ConnectionError
[英]except ConnectionError or TimeoutError not working
如果出現連接錯誤,我希望 Python 等待並重試。 這是相關代碼,其中“鏈接”是某個鏈接:
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)
除了我仍然定期收到連接錯誤。 而且我從來沒有看到文本“稍后會重試”,所以我知道代碼不會重試。 我究竟做錯了什么? 我在下面粘貼了部分錯誤代碼,以防我誤讀錯誤。 TIA!
TimeoutError: [WinError 10060] A connection attempt failed because the connected party didn't properly respond after a period time, or established connection failed because connected host has failed respond 超時錯誤:[WinError 10060] 連接嘗試失敗,因為連接方在一段時間后沒有正確響應,或者建立的連接失敗,因為連接的主機沒有響應
在處理上述異常的過程中,又出現了一個異常:
requests.packages.urllib3.exceptions.ProtocolError: ('Connection aborted.', TimeoutError(10060, 'A connection attempt failed because the connected party didn't properly respond after a period time, or established connection failed because connected host has failed to 連接失敗響應',無,10060,無))
在處理上述異常的過程中,又出現了一個異常:
requests.exceptions.ConnectionError: ('連接中止。', TimeoutError(10060, '連接嘗試失敗,因為連接方在一段時間后沒有正確響應,或者建立的連接失敗,因為連接的主機沒有響應', None , 10060, 無))
對我來說,在請求中使用自定義用戶代理可以解決這個問題。 使用這種方法可以欺騙您的瀏覽器。
作品:
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)
第二個請求不在 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))
我有同樣的問題。 事實證明 urlib3 依賴於 socket.py,它會引發 OSError。 所以,你需要明白這一點:
try:
r = requests.get(link)
except OSError as e:
print("There as an error: {}".format(e))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.