Python中利用aiohttp制作異步爬蟲及簡單應(yīng)用
摘要: 簡介 asyncio可以實現(xiàn)單線程并發(fā)IO操作,是Python中常用的異步處理模塊。關(guān)于asyncio模塊的介紹,筆者會在后續(xù)的文章中加以介紹,本文將會講述一個基于asyncio實現(xiàn)的HTTP框架——aiohttp,它可以幫助我們異步地實現(xiàn)HTTP請求,從而使得我們的程序效率大大提高。
簡介
asyncio可以實現(xiàn)單線程并發(fā)IO操作,是Python中常用的異步處理模塊。關(guān)于asyncio模塊的介紹,筆者會在后續(xù)的文章中加以介紹,本文將會講述一個基于asyncio實現(xiàn)的HTTP框架——aiohttp,它可以幫助我們異步地實現(xiàn)HTTP請求,從而使得我們的程序效率大大提高。
本文將會介紹aiohttp在爬蟲中的一個簡單應(yīng)用。
在原來的項目中,我們是利用Python的爬蟲框架scrapy來爬取當(dāng)當(dāng)網(wǎng)圖書暢銷榜的圖書信息的。在本文中,筆者將會以兩種方式來制作爬蟲,比較同步爬蟲與異步爬蟲(利用aiohttp實現(xiàn))的效率,展示aiohttp在爬蟲方面的優(yōu)勢。
同步爬蟲
首先,我們先來看看用一般的方法實現(xiàn)的爬蟲,即同步方法,完整的Python代碼如下:
''' 同步方式爬取當(dāng)當(dāng)暢銷書的圖書信息 ''' import time import requests import pandas as pd from bs4 import BeautifulSoup # table表格用于儲存書本信息 table = [] # 處理網(wǎng)頁 def download(url): html = requests.get(url).text # 利用BeautifulSoup將獲取到的文本解析成HTML soup = BeautifulSoup(html, "lxml") # 獲取網(wǎng)頁中的暢銷書信息 book_list = soup.find('ul', class_="bang_list clearfix bang_list_mode")('li') for book in book_list: info = book.find_all('div') # 獲取每本暢銷書的排名,名稱,評論數(shù),作者,出版社 rank = info[0].text[0:-1] name = info[2].text comments = info[3].text.split('條')[0] author = info[4].text date_and_publisher = info[5].text.split() publisher = date_and_publisher[1] if len(date_and_publisher) >= 2 else '' # 將每本暢銷書的上述信息加入到table中 table.append([rank, name, comments, author, publisher]) # 全部網(wǎng)頁 urls = ['http://bang.dangdang.com/books/bestsellers/01.00.00.00.00.00-recent7-0-0-1-%d' % i for i in range(1, 26)] # 統(tǒng)計該爬蟲的消耗時間 print('#' * 50) t1 = time.time() # 開始時間 for url in urls: download(url) # 將table轉(zhuǎn)化為pandas中的DataFrame并保存為CSV格式的文件 df = pd.DataFrame(table, columns=['rank', 'name', 'comments', 'author', 'publisher']) df.to_csv('E://douban/dangdang.csv', index=False) t2 = time.time() # 結(jié)束時間 print('使用一般方法,總共耗時:%s' % (t2 - t1)) print('#' * 50)
輸出結(jié)果如下:
##################################################
使用一般方法,總共耗時:23.522345542907715
##################################################
程序運行了23.5秒,爬取了500本書的信息,效率還是可以的。我們前往目錄中查看文件,如下:
異步爬蟲
接下來我們看看用aiohttp制作的異步爬蟲的效率,完整的源代碼如下:
''' 異步方式爬取當(dāng)當(dāng)暢銷書的圖書信息 ''' import time import aiohttp import asyncio import pandas as pd from bs4 import BeautifulSoup # table表格用于儲存書本信息 table = [] # 獲取網(wǎng)頁(文本信息) async def fetch(session, url): async with session.get(url) as response: return await response.text(encoding='gb18030') # 解析網(wǎng)頁 async def parser(html): # 利用BeautifulSoup將獲取到的文本解析成HTML soup = BeautifulSoup(html, "lxml") # 獲取網(wǎng)頁中的暢銷書信息 book_list = soup.find('ul', class_="bang_list clearfix bang_list_mode")('li') for book in book_list: info = book.find_all('div') # 獲取每本暢銷書的排名,名稱,評論數(shù),作者,出版社 rank = info[0].text[0:-1] name = info[2].text comments = info[3].text.split('條')[0] author = info[4].text date_and_publisher = info[5].text.split() publisher = date_and_publisher[1] if len(date_and_publisher) >=2 else '' # 將每本暢銷書的上述信息加入到table中 table.append([rank,name,comments,author,publisher]) # 處理網(wǎng)頁 async def download(url): async with aiohttp.ClientSession() as session: html = await fetch(session, url) await parser(html) # 全部網(wǎng)頁 urls = ['http://bang.dangdang.com/books/bestsellers/01.00.00.00.00.00-recent7-0-0-1-%d'%i for i in range(1,26)] # 統(tǒng)計該爬蟲的消耗時間 print('#' * 50) t1 = time.time() # 開始時間 # 利用asyncio模塊進(jìn)行異步IO處理 loop = asyncio.get_event_loop() tasks = [asyncio.ensure_future(download(url)) for url in urls] tasks = asyncio.gather(*tasks) loop.run_until_complete(tasks) # 將table轉(zhuǎn)化為pandas中的DataFrame并保存為CSV格式的文件 df = pd.DataFrame(table, columns=['rank','name','comments','author','publisher']) df.to_csv('E://douban/dangdang.csv',index=False) t2 = time.time() # 結(jié)束時間 print('使用aiohttp,總共耗時:%s' % (t2 - t1)) print('#' * 50)
我們可以看到,這個爬蟲與原先的一般方法的爬蟲的思路和處理方法基本一致,只是在處理HTTP請求時使用了aiohttp模塊以及在解析網(wǎng)頁時函數(shù)變成了協(xié)程(coroutine),再利用aysncio進(jìn)行并發(fā)處理,這樣無疑能夠提升爬蟲的效率。它的運行結(jié)果如下:
##################################################
使用aiohttp,總共耗時:2.405137538909912
##################################################
2.4秒,如此神奇?。?!再來看看文件的內(nèi)容:
總結(jié)
綜上可以看出,利用同步方法和異步方法制作的爬蟲的效率相差很大,因此,我們在實際制作爬蟲的過程中,也不妨可以考慮異步爬蟲,多多利用異步模塊,如aysncio, aiohttp。另外,aiohttp只支持3.5.3以后的Python版本。
- Python?async+request與async+aiohttp實現(xiàn)異步網(wǎng)絡(luò)請求探索
- python?基于aiohttp的異步爬蟲實戰(zhàn)詳解
- Python異步爬蟲requests和aiohttp中代理IP的使用
- python 基于AioHttp 異步抓取火星圖片
- Python中使用aiohttp模擬服務(wù)器出現(xiàn)錯誤問題及解決方法
- Python requests及aiohttp速度對比代碼實例
- Python aiohttp百萬并發(fā)極限測試實例分析
- python aiohttp的使用詳解
- Python中asyncio與aiohttp入門教程
- Python中aiohttp的簡單使用
相關(guān)文章
pytorch DistributedDataParallel 多卡訓(xùn)練結(jié)果變差的解決方案
這篇文章主要介紹了pytorch DistributedDataParallel 多卡訓(xùn)練結(jié)果變差的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-06-06Python標(biāo)準(zhǔn)庫之sys模塊用法詳解
“sys”即“system”,“系統(tǒng)”之意,該模塊提供了一些接口,用于訪問?Python?解釋器自身使用和維護(hù)的變量,同時模塊中還提供了一部分函數(shù),可以與解釋器進(jìn)行比較深度的交互,本文就給大家詳細(xì)的介紹一下Python?sys模塊,需要的朋友可以參考下2023-08-08Python簡單連接MongoDB數(shù)據(jù)庫的方法
這篇文章主要介紹了Python簡單連接MongoDB數(shù)據(jù)庫的方法,結(jié)合實例形式分析了Python使用pymongo模塊操作MongoDB數(shù)據(jù)庫的相關(guān)技巧,需要的朋友可以參考下2016-03-03Python?調(diào)用GPT-3?API實現(xiàn)過程詳解
這篇文章主要為大家介紹了Python?調(diào)用GPT-3?API實現(xiàn)過程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-02-02