1. 程式人生 > 實用技巧 >爬蟲神奇非同步爬蟲

爬蟲神奇非同步爬蟲

一、背景

有一個專案需要使用到爬蟲,因此去Google上搜索了一下,發現除了requests,scrapy,多執行緒,多程序以外,還有一種方法非同步爬蟲。使用aiohttp+async來進行網站的爬取。

二、使用

通過以下的指令安裝

# 通過指令安裝aiohttp
pip install aiohttp

我們在使用aiohttp的時候,還需要注意就是需要使用async這種非同步程式設計的方式。同時這個方法需要python3.5以上。主要是使用aiohttp這種非同步的方式來進行爬取。

採取一個不是很準確的圖

三、模型

3.1 多執行緒爬蟲模型

3.2 非同步爬蟲模型

四、核心程式碼

其實和一般的request爬蟲一樣,只是需要注意這裡需要使用aiohttp他是非同步程式設計的,因此需要用到async的方法

# 設定爬蟲的日誌格式
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s: %(message)s')
logger = logging.getLogger(__name__)

df = pd.DataFrame(columns=['occupation', 'companyName', 'location', 'salary', 'date', 'education', 'experience', 'companyType', 'companySize', 'type', 'request
']) # 非同步HTTP請求 async def fetch(sem11, session, url): async with sem11: async with session.get(url, headers=header) as response: return await response.text(errors='ignore') # 處理網頁 async def download(sem, url): async with aiohttp.ClientSession() as session: try: html
= await fetch(sem, session, url) # 這裡新增網頁的解析程式碼 await parser(html) except Exception as err: print(err) if __name__ == '__main__': # 統計該爬蟲的消耗時間 print('*' * 50) t_start_web = time.time() loop = asyncio.get_event_loop() sem1 = asyncio.Semaphore(100) # 第一個人 3413 # 第二個人 3413:6826 # 第三個人 6826: tasks = [asyncio.ensure_future(download(sem1, url)) for url in urls[:3413]] tasks = asyncio.gather(*tasks) loop.run_until_complete(tasks) t_end_web = time.time() print('網站爬取總共耗時:%s' % (t_end_web - t_start_web))

五、參考

5.1 詳細介紹

http://www.ityouknow.com/python/2019/12/28/python-aiohttp-102.html

https://www.jianshu.com/p/b8010594557f

5.2 效能對比

https://www.cnblogs.com/jiyongjia/p/9803991.html