Python爬虫的N种姿势 (2)

输出的结果如下(省略中间的输出,以......代替):

################################################## Larry Sanger , American former professor, co-founder of Wikipedia, founder of Citizendium and other projects Ken Jennings , American game show contestant and writer ...... Antoine de Saint-Exupery , French writer and aviator Michael Jackson , American singer, songwriter and dancer 并发方法,总共耗时:226.7499692440033 ##################################################

使用多线程并发后的爬虫执行时间约为227秒,大概是一般方法的三分之一的时间,速度有了明显的提升啊!多线程在速度上有明显提升,但执行的网页顺序是无序的,在线程的切换上开销也比较大,线程越多,开销越大。
  关于多线程与一般方法在速度上的比较,可以参考文章:Python爬虫之多线程下载豆瓣Top250电影图片。

异步方法

  异步方法在爬虫中是有效的速度提升手段,使用aiohttp可以异步地处理HTTP请求,使用asyncio可以实现异步IO,需要注意的是,aiohttp只支持3.5.3以后的Python版本。使用异步方法实现该爬虫的完整Python代码如下:

import requests from bs4 import BeautifulSoup import time import aiohttp import asyncio # 开始时间 t1 = time.time() print('#' * 50) url = "http://www.wikidata.org/w/index.php?title=Special:WhatLinksHere/Q5&limit=500&from=0" # 请求头部 headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36'} # 发送HTTP请求 req = requests.get(url, headers=headers) # 解析网页 soup = BeautifulSoup(req.text, "lxml") # 找到name和Description所在的记录 human_list = soup.find(id='mw-whatlinkshere-list')('li') urls = [] # 获取网址 for human in human_list: url = human.find('a')['href'] urls.append('https://www.wikidata.org'+url) # 异步HTTP请求 async def fetch(session, url): async with session.get(url) as response: return await response.text() # 解析网页 async def parser(html): # 利用BeautifulSoup将获取到的文本解析成HTML soup = BeautifulSoup(html, "lxml") # 获取name和description name = soup.find('span', class_="wikibase-title-label") desc = soup.find('span', class_="wikibase-descriptionview-text") if name is not None and desc is not None: print('%-40s,\t%s'%(name.text, desc.text)) # 处理网页,获取name和description async def download(url): async with aiohttp.ClientSession() as session: try: html = await fetch(session, url) await parser(html) except Exception as err: print(err) # 利用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) t2 = time.time() # 结束时间 print('使用异步,总共耗时:%s' % (t2 - t1)) print('#' * 50)

输出结果如下(省略中间的输出,以......代替):

################################################## Frédéric Taddeï , French journalist and TV host Gabriel Gonzáles Videla , Chilean politician ...... Denmark , sovereign state and Scandinavian country in northern Europe Usain Bolt , Jamaican sprinter and soccer player 使用异步,总共耗时:126.9002583026886 ##################################################

显然,异步方法使用了异步和并发两种提速方法,自然在速度有明显提升,大约为一般方法的六分之一。异步方法虽然效率高,但需要掌握异步编程,这需要学习一段时间。
  关于异步方法与一般方法在速度上的比较,可以参考文章:利用aiohttp实现异步爬虫。
  如果有人觉得127秒的爬虫速度还是慢,可以尝试一下异步代码(与之前的异步代码的区别在于:仅仅使用了正则表达式代替BeautifulSoup来解析网页,以提取网页中的内容):

import requests from bs4 import BeautifulSoup import time import aiohttp import asyncio import re # 开始时间 t1 = time.time() print('#' * 50) url = "http://www.wikidata.org/w/index.php?title=Special:WhatLinksHere/Q5&limit=500&from=0" # 请求头部 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36'} # 发送HTTP请求 req = requests.get(url, headers=headers) # 解析网页 soup = BeautifulSoup(req.text, "lxml") # 找到name和Description所在的记录 human_list = soup.find(id='mw-whatlinkshere-list')('li') urls = [] # 获取网址 for human in human_list: url = human.find('a')['href'] urls.append('https://www.wikidata.org' + url) # 异步HTTP请求 async def fetch(session, url): async with session.get(url) as response: return await response.text() # 解析网页 async def parser(html): # 利用正则表达式解析网页 try: name = re.findall(r'<span>(.+?)</span>', html)[0] desc = re.findall(r'<span>(.+?)</span>', html)[0] print('%-40s,\t%s' % (name, desc)) except Exception as err: pass # 处理网页,获取name和description async def download(url): async with aiohttp.ClientSession() as session: try: html = await fetch(session, url) await parser(html) except Exception as err: print(err) # 利用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) t2 = time.time() # 结束时间 print('使用异步(正则表达式),总共耗时:%s' % (t2 - t1)) print('#' * 50)

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wpzydf.html