[英]Python requests module gets stuck on requests.get() and gets timed out
[英]How to know for sure if requests.get has timed out?
在這行代碼中:
request = requests.get(url, verify=False, headers=headers, proxies=proxy, timeout=15)
我怎么知道timeout=15
已被觸發,以便我可以發送url
在 15 秒內未發送任何數據的消息?
如果在給定時間內根本沒有從服務器收到響應,則根據Exa來自其他答案的鏈接,拋出異常requests.exceptions.Timeout
。
為了測試這是否發生,我們可以使用try, except
塊來檢測它並采取相應的行動,而不是讓我們的程序崩潰。
擴展文檔中使用的演示:
import requests
try:
requests.get('https://github.com/', timeout=0.001)
except requests.exceptions.Timeout as e:
# code to run if we didn't get a reply
print("Request timed out!\nDetails:", e)
else:
# code to run if we did get a response, and only if we did.
print(r.headers)
只需在適當的地方替換您的網址和超時。
將拋出異常。 有關更多信息,請參閱此內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.