日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

Python爬虫还在写重试代码?快快学习下优雅的tenacity库!

發布時間:2024/9/15 python 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python爬虫还在写重试代码?快快学习下优雅的tenacity库! 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

前言

在爬蟲過程中,經常會由于一些網絡或其他不可控因素,從而遇到一些功能性問題。比如在發送請求時,會因為網絡不穩定,往往會有請求超時的問題。這種情況下,我們通常會在代碼中加入重試的代碼。重試的代碼本身不難實現,但如何寫得優雅、易用,是我們要考慮的問題。

Tenacity是一個通用的retry庫,簡化為任何任務加入重試的功能,它實現了幾乎我們可以使用到的所有重試場景。先pip為敬:

pip install tenacity

不懂這個庫怎么用, 很簡單,哦對了,可能還需要你知道裝飾器就是那個@啦就夠了,上菜!

無條件重試,重試之間無間隔

import tenacityimport requests# 直接加上retry裝飾器,代碼拋出異常會一直重試,直到代碼運行成功 @tenacity.retry() def baidu():response = requests.get(url = 'http://www.baidu.com')if response.status_code == 200:return response.textraise Exceptionres = baidu() print(res)

這里呢,我們使用requests請求了百度,并輸出response,在code=200的位置上,如果code不等于200,這個程序就會被retry重試。理就是這么個理,夠不夠優雅?

無條件重試,但是在重試之前要等待 3秒:

from tenacity import retry , stop_after_attempt , stop_after_delay , wait_fixedimport requests# 在程序重試前固定等待時間 @retry(wait = wait_fixed(3)) def baidu():web = requests.get(url = 'http://www.baidu.com')if web.status_code == 200:return web.textraise Exception res = baidu() print(res)

設置停止的基本條件

只重試3次

from tenacity import retry,stop_after_attemptimport requests# 加上終止條件的retry # 重試三次之后不再重試 @retry(stop=stop_after_attempt(3)) def baidu():res = requests.get(url = 'http://www.baidu.com')if res.status_code == 200:return res.textraise Exceptionweb = baidu() print(web)

這次呢還是訪問百度,但是加了一個條件,可以看到哈,重試三次之后不再重試,一般用于使用賬號密碼登錄的爬蟲,有的賬號一天只能登錄5次,超過5次就無法登錄了,

在運行程序的時候,使用retry + stop_after_attempt()簡直就是用了飄柔一樣的柔順啊!!!

重試5秒后不再重試

from tenacity import retry , stop_after_attempt , stop_after_delayimport requests# 指定5s重試間隔 @retry(stop=stop_after_delay(5)) def baidu():web = requests.get(url = 'http://www.baidu.com')if web.status_code == 200:return web.textraise Exception res = baidu() print(res)

用|連接多個重試條件

from tenacity import retry , stop_after_attempt , stop_after_delayimport requests# 使用'|' 連接多個條件組合使用@retry(stop=stop_after_delay(5) | stop_after_attempt(3)) def baidu():web = requests.get(url = 'http://www.baidu.com')if web.status_code == 200:return web.textraise Exception res = baidu() print(res)

在重試前設置隨機等待時間

from tenacity import retry , stop_after_attempt , stop_after_delay , wait_fixed , wait_randomimport requests# 在程序重試前設置隨機等待時間 @retry(wait = wait_random(min=1,max=2)) def baidu():web = requests.get(url = 'http://www.baidu.com')if web.status_code == 200:return web.textraise Exception res = baidu() print(res)

按照指定數等待時間

from tenacity import retry , stop_after_attempt , stop_after_delay , wait_fixed , wait_random , wait_exponentialimport requests# 按照指定數等待時間 @retry(wait = wait_exponential(multiplier=2,min = 3,max = 100)) def baidu():web = requests.get(url = 'http://www.baidu.com')if web.status_code == 200:return web.textraise Exception res = baidu() print(res)

有觸發條件的retry語句

from tenacity import retry ,retry_if_exception_type ,retry_if_resultimport requests# 有觸發條件的retry語句@ retry(retry = retry_if_exception_type(IOError)) def fun_1():print('巴拉巴拉巴拉巴拉')raise Exceptiondef fun_2(value):return value is None@ retry(retry = retry_if_exception_type(fun_2)) def fun_3():print('滴滴滴滴滴')@ retry(retry=(retry_if_result(fun_2)|retry_if_exception_type())) def fun_4():print('呼呼呼呼呼呼')

在retry前后增加log

from tenacity import retry , stop_after_attempt ,before_log ,after_log , before_sleep_log import logginglogger = logging.getLogger(__name__)@ retry(stop = stop_after_attempt(3),before = before_log(logger,logging.DEBUG)) def fun_1():raise Exception('Error')@ retry(stop = stop_after_attempt(3),after = after_log(logger,logging.DEBUG)) def fun_2():raise Exception('Error') @ retry(stop = stop_after_attempt(3),before_sleep = before_sleep_log(logger,logging.DEBUG)) def fun_3():raise Exception('Error')

就是這么easy~~~~~~

推薦閱讀 平時都逛哪些技術網站?(程序員必備58個網站匯總)肝!精心整理了 50 個數據源網站!3種Python數據結構,13種創建方法,這個總結,超贊!

總結

以上是生活随笔為你收集整理的Python爬虫还在写重试代码?快快学习下优雅的tenacity库!的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。