自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

利用aiohttp制作異步爬蟲

開發(fā) 后端
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代碼如下: 

  1. '''  
  2. 同步方式爬取當(dāng)當(dāng)暢銷書的圖書信息  
  3. '''  
  4. import time  
  5. import requests  
  6. import pandas as pd  
  7. from bs4 import BeautifulSoup  
  8. # table表格用于儲存書本信息  
  9. table = []  
  10. # 處理網(wǎng)頁  
  11. def download(url):  
  12.     html = requests.get(url).text  
  13.     # 利用BeautifulSoup將獲取到的文本解析成HTML  
  14.     soup = BeautifulSoup(html, "lxml")  
  15.     # 獲取網(wǎng)頁中的暢銷書信息  
  16.     book_list = soup.find('ul', class_="bang_list clearfix bang_list_mode")('li')  
  17.     for book in book_list:  
  18.         info = book.find_all('div')  
  19.         # 獲取每本暢銷書的排名,名稱,評論數(shù),作者,出版社  
  20.         rank = info[0].text[0:-1]  
  21.         name = info[2].text  
  22.         comments = info[3].text.split('條')[0]  
  23.         author = info[4].text  
  24.         date_and_publisher = info[5].text.split()  
  25.         publisher = date_and_publisher[1] if len(date_and_publisher) >= 2 else ''  
  26.         # 將每本暢銷書的上述信息加入到table中  
  27.         table.append([rank, name, comments, author, publisher])  
  28. # 全部網(wǎng)頁  
  29. 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)]  
  30. # 統(tǒng)計(jì)該爬蟲的消耗時(shí)間  
  31. print('#' * 50)  
  32. t1 = time.time()  # 開始時(shí)間  
  33. for url in urls:  
  34.     download(url)  
  35. # 將table轉(zhuǎn)化為pandas中的DataFrame并保存為CSV格式的文件 
  36.  
  37. df = pd.DataFrame(table, columns=['rank', 'name', 'comments', 'author', 'publisher'])  
  38. df.to_csv('E://douban/dangdang.csv', index=False 
  39. t2 = time.time()  # 結(jié)束時(shí)間  
  40. print('使用一般方法,總共耗時(shí):%s' % (t2 - t1))  
  41. print('#' * 50) 

輸出結(jié)果如下: 

  1. ##################################################  
  2. 使用一般方法,總共耗時(shí):23.522345542907715  
  3. ################################################## 

程序運(yùn)行了23.5秒,爬取了500本書的信息,效率還是可以的。我們前往目錄中查看文件,如下:

異步爬蟲

接下來我們看看用aiohttp制作的異步爬蟲的效率,完整的源代碼如下: 

  1. '''  
  2. 異步方式爬取當(dāng)當(dāng)暢銷書的圖書信息  
  3. '''  
  4. import time  
  5. import aiohttp  
  6. import asyncio  
  7. import pandas as pd  
  8. from bs4 import BeautifulSoup  
  9. # table表格用于儲存書本信息  
  10. table = []  
  11. # 獲取網(wǎng)頁(文本信息)  
  12. async def fetch(session, url):  
  13.     async with session.get(url) as response:  
  14.         return await response.text(encoding='gb18030' 
  15. # 解析網(wǎng)頁  
  16. async def parser(html):  
  17.     # 利用BeautifulSoup將獲取到的文本解析成HTML  
  18.     soup = BeautifulSoup(html, "lxml")  
  19.     # 獲取網(wǎng)頁中的暢銷書信息  
  20.     book_list = soup.find('ul', class_="bang_list clearfix bang_list_mode")('li')  
  21.     for book in book_list:  
  22.         info = book.find_all('div')  
  23.         # 獲取每本暢銷書的排名,名稱,評論數(shù),作者,出版社  
  24.         rank = info[0].text[0:-1]  
  25.         name = info[2].text  
  26.         comments = info[3].text.split('條')[0]  
  27.         author = info[4].text  
  28.         date_and_publisher = info[5].text.split()  
  29.         publisher = date_and_publisher[1] if len(date_and_publisher) >=2 else ''  
  30.         # 將每本暢銷書的上述信息加入到table中  
  31.         table.append([rank,name,comments,author,publisher])  
  32. # 處理網(wǎng)頁      
  33. async def download(url):  
  34.     async with aiohttp.ClientSession() as session:  
  35.         html = await fetch(session, url)  
  36.         await parser(html)  
  37. # 全部網(wǎng)頁  
  38. 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)]  
  39. # 統(tǒng)計(jì)該爬蟲的消耗時(shí)間  
  40. print('#' * 50)  
  41. t1 = time.time() # 開始時(shí)間  
  42. # 利用asyncio模塊進(jìn)行異步IO處理  
  43. loop = asyncio.get_event_loop()  
  44. tasks = [asyncio.ensure_future(download(url)) for url in urls]  
  45. tasks = asyncio.gather(*tasks)  
  46. loop.run_until_complete(tasks)  
  47. # 將table轉(zhuǎn)化為pandas中的DataFrame并保存為CSV格式的文件  
  48. df = pd.DataFrame(table, columns=['rank','name','comments','author','publisher'])  
  49. df.to_csv('E://douban/dangdang.csv',index=False 
  50. t2 = time.time() # 結(jié)束時(shí)間  
  51. print('使用aiohttp,總共耗時(shí):%s' % (t2 - t1))  
  52. print('#' * 50) 

我們可以看到,這個(gè)爬蟲與原先的一般方法的爬蟲的思路和處理方法基本一致,只是在處理HTTP請求時(shí)使用了aiohttp模塊以及在解析網(wǎng)頁時(shí)函數(shù)變成了協(xié)程(coroutine),再利用aysncio進(jìn)行并發(fā)處理,這樣無疑能夠提升爬蟲的效率。它的運(yùn)行結(jié)果如下: 

  1. ##################################################  
  2. 使用aiohttp,總共耗時(shí):2.405137538909912  
  3. ################################################## 

2.4秒,如此神奇?。?!再來看看文件的內(nèi)容:

總結(jié)

綜上可以看出,利用同步方法和異步方法制作的爬蟲的效率相差很大,因此,我們在實(shí)際制作爬蟲的過程中,也不妨可以考慮異步爬蟲,多多利用異步模塊,如aysncio, aiohttp。另外,aiohttp只支持3.5.3以后的Python版本。

當(dāng)然,本文只是作為一個(gè)異步爬蟲的例子,并沒有具體講述異步背后的故事,而異步的思想在我們現(xiàn)實(shí)生活和網(wǎng)站制作等方面有著廣泛的應(yīng)用,本文到此結(jié)束,歡迎大家交流~ 

責(zé)任編輯:龐桂玉 來源: Python中文社區(qū)
相關(guān)推薦

2023-08-30 08:43:42

asyncioaiohttp

2024-04-30 11:11:33

aiohttp模塊編程

2014-03-11 11:21:23

2018-01-30 18:15:12

Python網(wǎng)絡(luò)爬蟲gevent

2022-02-12 21:05:11

異步爬蟲框架

2009-08-20 10:55:59

2010-03-09 09:32:20

Python網(wǎng)頁爬蟲

2011-02-22 10:00:38

.NETc#IronPython

2012-06-14 14:42:42

JavaScript

2011-11-16 13:22:38

Jscex

2021-03-01 08:33:39

插件庫弱符號程序

2016-11-11 14:16:12

onionScan爬蟲

2017-08-11 06:40:07

深度學(xué)習(xí)機(jī)器學(xué)習(xí)照片

2021-03-18 09:18:12

python爬蟲

2025-04-27 04:05:00

AI模型爬蟲

2020-11-03 10:35:39

Python

2021-11-03 18:01:21

Python爬蟲微信群

2020-11-11 10:58:59

Scrapy

2025-03-12 05:00:00

PythonaiohttpHTTP

2022-03-03 08:30:41

GeneratorES6函數(shù)
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號