利用aiohttp製做異步爬蟲

  asyncio能夠實現單線程併發IO操做,是Python中經常使用的異步處理模塊。關於asyncio模塊的介紹,筆者會在後續的文章中加以介紹,本文將會講述一個基於asyncio實現的HTTP框架——aiohttp,它能夠幫助咱們異步地實現HTTP請求,從而使得咱們的程序效率大大提升。
  本文將會介紹aiohttp在爬蟲中的一個簡單應用。
  咱們的項目來源於:Scrapy爬蟲(5)爬取噹噹網圖書暢銷榜,在原來的項目中,咱們是利用Python的爬蟲框架scrapy來爬取噹噹網圖書暢銷榜的圖書信息的。在本文中,筆者將會以兩種方式來製做爬蟲,比較同步爬蟲與異步爬蟲(利用aiohttp實現)的效率,展現aiohttp在爬蟲方面的優點。
  首先,咱們先來看看用通常的方法實現的爬蟲,即同步方法,完整的Python代碼以下:html

'''
同步方式爬取噹噹暢銷書的圖書信息
'''

import time
import requests
import pandas as pd
from bs4 import BeautifulSoup

# table表格用於儲存書本信息
table = []

# 處理網頁
def download(url):
    html = requests.get(url).text

    # 利用BeautifulSoup將獲取到的文本解析成HTML
    soup = BeautifulSoup(html, "lxml")
    # 獲取網頁中的暢銷書信息
    book_list = soup.find('ul', class_="bang_list clearfix bang_list_mode")('li')

    for book in book_list:
        info = book.find_all('div')

        # 獲取每本暢銷書的排名,名稱,評論數,做者,出版社
        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])


# 所有網頁
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)]

# 統計該爬蟲的消耗時間
print('#' * 50)
t1 = time.time()  # 開始時間

for url in urls:
    download(url)

# 將table轉化爲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()  # 結束時間
print('使用通常方法,總共耗時:%s' % (t2 - t1))
print('#' * 50)

輸出結果以下:python

##################################################
使用通常方法,總共耗時:23.522345542907715
##################################################

程序運行了23.5秒,爬取了500本書的信息,效率仍是能夠的。
  咱們前往目錄中查看文件,以下:web

  接下來咱們看看用aiohttp製做的異步爬蟲的效率,完整的源代碼以下:編程

'''
異步方式爬取噹噹暢銷書的圖書信息
'''

import time
import aiohttp
import asyncio
import pandas as pd
from bs4 import BeautifulSoup

# table表格用於儲存書本信息
table = []

# 獲取網頁(文本信息)
async def fetch(session, url):
    async with session.get(url) as response:
        return await response.text(encoding='gb18030')

# 解析網頁
async def parser(html):
    
    # 利用BeautifulSoup將獲取到的文本解析成HTML
    soup = BeautifulSoup(html, "lxml")
    # 獲取網頁中的暢銷書信息
    book_list = soup.find('ul', class_="bang_list clearfix bang_list_mode")('li')

    for book in book_list:
        
        info = book.find_all('div')

        # 獲取每本暢銷書的排名,名稱,評論數,做者,出版社
        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])
        
# 處理網頁    
async def download(url):
    async with aiohttp.ClientSession() as session:
        html = await fetch(session, url)
        await parser(html)

# 所有網頁
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)]

# 統計該爬蟲的消耗時間
print('#' * 50)
t1 = time.time() # 開始時間

# 利用asyncio模塊進行異步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轉化爲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() # 結束時間
print('使用aiohttp,總共耗時:%s' % (t2 - t1))
print('#' * 50)

咱們能夠看到,這個爬蟲與原先的通常方法的爬蟲的思路和處理方法基本一致,只是在處理HTTP請求時使用了aiohttp模塊以及在解析網頁時函數變成了協程(coroutine),再利用aysncio進行併發處理,這樣無疑可以提高爬蟲的效率。它的運行結果以下:微信

##################################################
使用aiohttp,總共耗時:2.405137538909912
##################################################

2.4秒,如此神奇!!!再來看看文件的內容:session

  綜上能夠看出,利用同步方法和異步方法制做的爬蟲的效率相差很大,所以,咱們在實際製做爬蟲的過程當中,也不妨能夠考慮異步爬蟲,多多利用異步模塊,如aysncio, aiohttp。另外,aiohttp只支持3.5.3之後的Python版本。
  固然,本文只是做爲一個異步爬蟲的例子,並無具體講述異步背後的故事,而異步的思想在咱們現實生活和網站製做等方面有着普遍的應用,筆者將會以本身的理解來介紹異步編程,歡迎你們關注。
  本文到此結束,歡迎你們關注微信公衆號: 輕鬆學會Python爬蟲(微信號爲:easy_web_scrape)。歡迎交流~併發

相關文章
相關標籤/搜索