摘要: 簡介 asyncio可以實(shí)現(xiàn)單線程并發(fā)IO操作,是Python中常用的異步處理模塊。關(guān)于asyncio模塊的介紹,筆者會在后續(xù)的文章中加以介紹,本文將會講述一個(gè)基于asyncio實(shí)現(xiàn)的HTTP框架——aiohttp,它可以幫助我們異步地實(shí)現(xiàn)HTTP請求,從而使得我們的程序效率大大提高。
簡介
asyncio可以實(shí)現(xiàn)單線程并發(fā)IO操作,是Python中常用的異步處理模塊。關(guān)于asyncio模塊的介紹,筆者會在后續(xù)的文章中加以介紹,本文將會講述一個(gè)基于asyncio實(shí)現(xiàn)的HTTP框架——aiohttp,它可以幫助我們異步地實(shí)現(xiàn)HTTP請求,從而使得我們的程序效率大大提高。
本文將會介紹aiohttp在爬蟲中的一個(gè)簡單應(yīng)用。
在原來的項(xiàng)目中,我們是利用Python的爬蟲框架scrapy來爬取當(dāng)當(dāng)網(wǎng)圖書暢銷榜的圖書信息的。在本文中,筆者將會以兩種方式來制作爬蟲,比較同步爬蟲與異步爬蟲(利用aiohttp實(shí)現(xiàn))的效率,展示aiohttp在爬蟲方面的優(yōu)勢。
同步爬蟲
首先,我們先來看看用一般的方法實(shí)現(xiàn)的爬蟲,即同步方法,完整的Python代碼如下:
'''同步方式爬取當(dāng)當(dāng)暢銷書的圖書信息'''import timeimport requestsimport pandas as pdfrom bs4 import BeautifulSoup# table表格用于儲存書本信息table = []# 處理網(wǎng)頁def download(url):html = requests.get(url).text# 利用BeautifulSoup將獲取到的文本解析成HTMLsoup = 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].textcomments = info[3].text.split('條')[0]author = info[4].textdate_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)計(jì)該爬蟲的消耗時(shí)間print('#' * 50)t1 = time.time() # 開始時(shí)間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é)束時(shí)間print('使用一般方法,總共耗時(shí):%s' % (t2 - t1))print('#' * 50)
輸出結(jié)果如下:
##################################################
使用一般方法,總共耗時(shí):23.522345542907715
##################################################
程序運(yùn)行了23.5秒,爬取了500本書的信息,效率還是可以的。我們前往目錄中查看文件,如下:
新聞熱點(diǎn)
疑難解答
圖片精選