前言
“由于連接方在一段時間后沒有正確答復或連接的主機沒有反應,連接嘗試失敗”,這是經(jīng)常遇到的問題requests.exceptions.ConnectionError: HTTPSConnectionPool(host='www.github.com', port=443): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x0000020F06524AC8>: Failed to establish a new connection: [WinError 10060] 由于連接方在一段時間后沒有正確答復或連接的主機沒有反應,連接嘗試失敗。',))
一般出現(xiàn)這個問題的原因是:host='www.github.com' 主機地址沒連上,使用 requests 發(fā)請求時,有些網(wǎng)站服務器不穩(wěn)定,特別是國外的網(wǎng)站,經(jīng)常會出現(xiàn)連接失敗情況。
連接失敗后,有時候會拋出上面異常,有時候會一直卡住,進入假死狀態(tài),沒響應,也不會結束。
timeout
requests發(fā)請求的時候有個默認的超時時間,這個時間在20秒左右
import requests
s=requests.session()
url="https://www.github.com/"
r=s.request("GET",url=url)
print(r.text)
連不上服務器會出現(xiàn)異常:requests.exceptions.ConnectionError
requests.exceptions.ConnectionError: HTTPSConnectionPool(host``=``'www.github.com'``, port``=``443``): ``Max retries exceeded with url: ``/ (Caused by NewConnectionError(``'<urllib3.connection.VerifiedHTTPSConnection object at 0x0000020F06524AC8>: Failed to establish a new connection: [WinError 10060] 由于連接方在一段時間后沒有正確答復或連接的主機沒有反應,連接嘗試失敗。'``,))
|
如果請求一直沒響應,進入假死狀態(tài),可以加個timeout超時時間,達到這個請求超時時間就結束,如0.1s超時
import requests
s=requests.session()
url="https://www.github.com/"
r=s.request("GET",url=url,timeout=0.1)
print(r.text)
|
這樣拋出的異常是:requests.exceptions.ConnectTimeout
raise ConnectTimeout(e, request``=``request)
requests.exceptions.ConnectTimeout: HTTPSConnectionPool(host``=``'www.github.com'``, port``=``443``): ``Max retries exceeded with url: ``/ (Caused by ConnectTimeoutError(<urllib3.connection.VerifiedHTTPSConnection ``object at ``0x0000000003472358``>, ``'Connection to www.github.com timed out. (connect timeout=0.1)'``))
** 失敗重試 max_retries**
Requests自帶了一個傳輸適配器,也就是HTTPAdapter。這個適配器使用了強大的urllib3, 為Requests提供了默認的HTTP和HTTPS交互。
每當Session被初始化,就會有適配器附著在Session上,其中一個供HTTP使用,另一個供HTTPS使用。
import requests
from requests.exceptions import ConnectTimeout
from requests.adapters import HTTPAdapter
import time
s=requests.session()
s.mount('http://',HTTPAdapter(max_retries=3))#重試3次, 在第一次的基礎上增加次數(shù),一共發(fā)送4次
s.mount('https://',HTTPAdapter(max_retries=3))
a = time.time()
url="http://124.0.1.0:8000/"
try:
r=s.request("GET",url=url ,timeout=10)
print(r.text)
except ConnectTimeout as e:
print(111)
print(time.time() -a)
這樣每次請求超過0.1s,超過時,會重試3次,最大請求時長0.1s
文字從 https://www.cnblogs.com/canglongdao/p/13454007.html 復制粘貼, 有問題請聯(lián)系刪除