錯誤提示:
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='baike.baidu.com', port=443):
Max retries exceeded with url: https://baike.baidu.com/item/%E5%88%98%E5%BE%B7%E5%8D%8E/114923
(Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7fb51433af98>:
Failed to establish a new connection: [Errno -2] Name or service not known',))
經(jīng)過一番查詢,發(fā)現(xiàn)該錯誤是因為如下:
http的連接數(shù)超過最大限制儡嘶,默認的情況下連接是Keep-alive的张峰,所以這就導(dǎo)致了服務(wù)器保持了太多連接而不能再新建連接。
ip被封
程序請求速度過快堪簿。
解決辦法如下:
第一種方法
try:
page1 = requests.get(ap)
except requests.exceptions.ConnectionError:
r.status_code = "Connection refused"
第二種方法:
request的連接數(shù)過多而導(dǎo)致Max retries exceeded
在header中不使用持久連接
'Connection': 'close'
或
requests.adapters.DEFAULT_RETRIES = 5
第三種方法:
針對請求請求速度過快導(dǎo)致程序報錯痊乾。
解決方法可以參考以下例子:
import time
while 1:
try:
page = requests.get(url)
except:
print("Connection refused by the server..")
print("Let me sleep for 5 seconds")
print("ZZzzzz...")
time.sleep(5)
print("Was a nice sleep, now let me continue...")
continue
原文網(wǎng)址:www.chenxm.cc/post/536.html