利用aiohttp制作异步爬虫!

简介 asyncio可以实现单线程并发IO操作,是Python中常用的异步处理模块。关于asyncio模块的介绍,笔者会在后续的文章中加以介绍,本文将会讲述一个基于asyncio实现的HTTP框架——aiohttp,它可以帮助我们异步地实现HTTP请求,从而使得我们的程序效率大大提高。 本文将会介绍aiohttp在爬虫中的一个简单应用。 在原来的项目中,我们是利用Python的爬虫框架scrapy来爬取当当网图书畅销榜的图书信息的。在本文中,笔者将会以两种方式来制作爬虫,比较同步爬虫与异步爬虫(利用aiohttp实现)的效率,展示aiohttp在爬虫方面的优势。 同步爬虫 首先,我们先来看看用一般的方法实现的爬虫,即同步方法,完整的Python代码如下:

进群:960410445  即可获取数十套PDF!

'''

同步方式爬取当当畅销书的图书信息

'''

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)

输出结果如下:

##################################################

使用一般方法,总共耗时:23.522345542907715

##################################################

程序运行了23.5秒,爬取了500本书的信息,效率还是可以的。我们前往目录中查看文件,如下:

异步爬虫

接下来我们看看用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秒,如此神奇!!!再来看看文件的内容:

总结 综上可以看出,利用同步方法和异步方法制作的爬虫的效率相差很大,因此,我们在实际制作爬虫的过程中,也不妨可以考虑异步爬虫,多多利用异步模块,如aysncio, aiohttp。另外,aiohttp只支持3.5.3以后的Python版本。

猜你喜欢

转载自blog.csdn.net/qq_42156420/article/details/85615269