最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python requests請求超時的解決方案

 更新時間:2024年12月17日 09:38:03   作者:IT之一小佬  
在進(jìn)行網(wǎng)絡(luò)數(shù)據(jù)爬取過程中,網(wǎng)絡(luò)請求超時是一個令人頭疼的問題,尤其在Python中,我們常常需要應(yīng)對各種網(wǎng)絡(luò)爬蟲、API調(diào)用或其他網(wǎng)絡(luò)操作,而網(wǎng)絡(luò)請求超時的原因千奇百怪,在本篇文章中,我們將深入探討Python requests請求超時的解決方案,需要的朋友可以參考下

python程序根據(jù)url從互聯(lián)網(wǎng)上批量獲取數(shù)據(jù)時,設(shè)置HTTP或Socket超時,來防止爬蟲爬取某個頁面時間過長,導(dǎo)致程序卡置不前。

1、socket

全局設(shè)置。

import socket
 
socket.setdefaulttimeout(1)

t:代表經(jīng)過t秒后,如果還未下載成功,自動跳入下一次操作,此次下載失敗 。

2、添加timeout

使用timeout 參數(shù)可以設(shè)定等待連接的秒數(shù),如果等待超時,Requests會拋出異常。

示例代碼1:

import requests
 
res = requests.get('https://github.com', timeout=0.01)
print(res)

運(yùn)行結(jié)果:

示例代碼2:

import requests
 
res = requests.get('https://github.com', timeout=10)
print(res)

運(yùn)行結(jié)果: 

注意:timeout 僅對連接過程有效,與響應(yīng)體的下載無關(guān)。 timeout 并不是整個下載響應(yīng)的時間限制,而是如果服務(wù)器在 timeout 秒內(nèi)沒有應(yīng)答,將會引發(fā)一個異常(更精確地說,是在 timeout 秒內(nèi)沒有從基礎(chǔ)套接字上接收到任何字節(jié)的數(shù)據(jù)時)。

3、HTTPAdapter(max_retries=3)重試

示例代碼:

import time
import requests
from requests.adapters import HTTPAdapter
 
 
s = requests.Session()
s.mount('http://', HTTPAdapter(max_retries=3))
s.mount('https://', HTTPAdapter(max_retries=3))
 
print(time.strftime('%Y-%m-%d %H:%M:%S'))
 
try:
    res = s.get('https://github.com', timeout=2)
    print(res)
except requests.exceptions.RequestException as e:
    print(e)
 
print(time.strftime('%Y-%m-%d %H:%M:%S'))

運(yùn)行結(jié)果:

注意:max_retries 為最大重試次數(shù),重試3次,加上最初的一次請求,一共是4次,所以上述代碼運(yùn)行耗時至少是8秒而不是6秒。

4、捕捉異常

示例代碼1:

import requests
 
 
def get_html(url, timeout=5):
    i = 0
    while i < 3:
        try:
            html = requests.get(url, timeout=timeout)
            return html.text
        except requests.exceptions.RequestException as e:
            i += 1
            print(e)
 
 
res = get_html('https://github.com', timeout=0.1)
print(res)

運(yùn)行結(jié)果:

示例代碼2:  【試圖提大timeout的值】

import requests
 
 
def get_html(url, timeout=5):
    i = 0
    while i < 3:
        try:
            html = requests.get(url, timeout=timeout)
            return html.text
        except requests.exceptions.RequestException as e:
            i += 1
            print(e)
 
 
res = get_html('https://github.com', timeout=10)
print(res)

運(yùn)行結(jié)果:

到此這篇關(guān)于Python requests請求超時的解決方案的文章就介紹到這了,更多相關(guān)Python requests請求超時內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論

巫溪县| 恩平市| 文成县| 丹寨县| 乃东县| 阿巴嘎旗| 十堰市| 文山县| 金塔县| 平度市| 柳河县| 闽侯县| 吉首市| 石狮市| 呼和浩特市| 武山县| 津市市| 苏尼特右旗| 义乌市| 班玛县| 雷州市| 禄劝| 仪陇县| 安远县| 广河县| 广昌县| 若羌县| 壤塘县| 海城市| 贵阳市| 庄河市| 化州市| 峨边| 浏阳市| 卢龙县| 菏泽市| 延川县| 揭东县| 南平市| 文安县| 新兴县|