python爬蟲控制aiohttp并發(fā)數量方式
更新時間:2024年06月27日 10:48:16 作者:NULL_1969
這篇文章主要介紹了python爬蟲控制aiohttp并發(fā)數量方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
前言
在使用aiohttp并發(fā)訪問多個頁面時效率,明顯比串行requests快很多,
但是也存在一個問題,就是網站檢測到短時間內請求的數量過多會導致頁面請求不成成功,
頁面返回429 (too many requests)。
解決上述問題
目前想到兩個方法
1、控制請求的時間,用sleep延時,來消耗每一次訪問的時間,減少單位時間內的訪問量,這樣肯定是可以,但效率太低
2、控制并發(fā)數量,控制并發(fā)數量,普遍推薦用信號量來控制使用方法也比較簡單如下:
from asyncio import tasks
from aiohttp.client import ClientSession
from lxml import etree
from time import sleep
import time
import asyncio
import aiohttp
async def read_page_list(page_num,sem):
params = {
'page':page_num,
}
#通過連接池控制并發(fā)數量 limit 默認為100 0 為無限制
async with sem:
try:
async with aiohttp.ClientSession() as session:
async with session.get(url=url,params=params,headers=headers) as response:
text = await response.text()
except Exception as e:
print('exception:',e)
tree = etree.HTML(text)
page_list = tree.xpath('//*[@id="thumbs"]/section[1]/ul/li')
# break
for li in page_list:
pic_small_url = li.xpath('.//img/@data-src')[0]
# print(pic_small_url,type(pic_small_url))
# pic_small_url = str(pic_small_url)
if 'small' in pic_small_url:
temp_url = pic_small_url.replace('small','full')
a = temp_url.rfind('/')
temp_url1= temp_url[:a]
pic_full_url = temp_url1+'/wallhaven-'+temp_url.split('/')[-1]
pic_full_url = pic_full_url.replace('th','w')
# print(page_num,pic_full_url)
pic_list.append(pic_full_url)
else:
print(page_num,'find small error',pic_small_url)
print(page_num,len(page_list),response.status)
# await asyncio.sleep(1)
#這里可以用硬延時來控制程序的訪問速度,進而控制單位時間內并發(fā)的數量
# sleep(0.5)
#定義信號量
sem = asyncio.Semaphore(2)
start = time.time()
#建立任務列表
tasks = [loop.create_task(read_page_list(i,sem)) for i in range(1,20)]
loop.run_until_complete(asyncio.wait(tasks))
print('get page list use time:',time.time()-start)
實驗結果
如下:
- 經試驗只有當請求頁面20個 sem=1時才不會出現服務器返回429.
- 當把請求頁面數量改為10 sem=5是就不會出現服務返回429的情況
總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Python自定義聚合函數merge與transform區(qū)別詳解
這篇文章主要介紹了Python自定義聚合函數merge與transform區(qū)別詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-05-05
Pytorch中torch.flatten()和torch.nn.Flatten()實例詳解
這篇文章主要給大家介紹了關于Pytorch中torch.flatten()和torch.nn.Flatten()的相關資料,文中通過實例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2022-02-02
PyTorch深度學習LSTM從input輸入到Linear輸出
這篇文章主要為大家介紹了PyTorch深度學習LSTM從input輸入到Linear輸出深入理解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-05-05

