当前位置:   article > 正文

Python爬虫的N种姿势

Python爬虫的N种姿势

爬虫的N中姿势

首先,分析来爬虫的思路:先在第一个网页(https://www.wikidata.org/w/index.php?title=Special:WhatLinksHere/Q5&limit=500&from=0)中得到500个名人所在的网址,接下来就爬取这500个网页中的名人的名字及描述,如无描述,则跳过。
接下来,我们将介绍实现这个爬虫的4种方法,并分析它们各自的优缺点,希望能让读者对爬虫有更多的体会。实现爬虫的方法为:

  • 一般方法(同步,requests+BeautifulSoup)
  • 并发(使用concurrent.futures模块以及requests+BeautifulSoup)
  • 异步(使用aiohttp+asyncio+requests+BeautifulSoup)
  • 使用框架Scrapy

一般方法

一般方法即为同步方法,主要使用requests+BeautifulSoup,按顺序执行。完整的Python代码如下:

  1. import requests
  2. from bs4 import BeautifulSoup
  3. import time
  4. # 开始时间
  5. t1 = time.time()
  6. print('#' * 50)
  7. url = "http://www.wikidata.org/w/index.php?title=Special:WhatLinksHere/Q5&limit=500&from=0"
  8. # 请求头部
  9. 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'}
  10. # 发送HTTP请求
  11. req = requests.get(url, headers=headers)
  12. # 解析网页
  13. soup = BeautifulSoup(req.text, "lxml")
  14. # 找到name和Description所在的记录
  15. human_list = soup.find(id='mw-whatlinkshere-list')('li')
  16. urls = []
  17. # 获取网址
  18. for human in human_list:
  19. url = human.find('a')['href']
  20. urls.append('https://www.wikidata.org'+url)
  21. # 获取每个网页的name和description
  22. def parser(url):
  23. req = requests.get(url)
  24. # 利用BeautifulSoup将获取到的文本解析成HTML
  25. soup = BeautifulSoup(req.text, "lxml")
  26. # 获取name和description
  27. name = soup.find('span', class_="wikibase-title-label")
  28. desc = soup.find('span', class_="wikibase-descriptionview-text")
  29. if name is not None and desc is not None:
  30. print('%-40s,\t%s'%(name.text, desc.text))
  31. for url in urls:
  32. parser(url)
  33. t2 = time.time() # 结束时间
  34. print('一般方法,总共耗时:%s' % (t2 - t1))
  35. print('#' * 50)

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

  1. ##################################################
  2. George Washington , first President of the United States
  3. Douglas Adams , British author and humorist (19522001)
  4. ......
  5. Willoughby Newton , Politician from Virginia, USA
  6. Mack Wilberg , American conductor
  7. 一般方法,总共耗时:724.9654655456543
  8. ##################################################

使用同步方法,总耗时约725秒,即12分钟多。
一般方法虽然思路简单,容易实现,但效率不高,耗时长。那么,使用并发试试看。

并发方法

并发方法使用多线程来加速一般方法,我们使用的并发模块为concurrent.futures模块,设置多线程的个数为20个(实际不一定能达到,视计算机而定)。完整的Python代码如下:

  1. import requests
  2. from bs4 import BeautifulSoup
  3. import time
  4. from concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED
  5. # 开始时间
  6. t1 = time.time()
  7. print('#' * 50)
  8. url = "http://www.wikidata.org/w/index.php?title=Special:WhatLinksHere/Q5&limit=500&from=0"
  9. # 请求头部
  10. 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'}
  11. # 发送HTTP请求
  12. req = requests.get(url, headers=headers)
  13. # 解析网页
  14. soup = BeautifulSoup(req.text, "lxml")
  15. # 找到name和Description所在的记录
  16. human_list = soup.find(id='mw-whatlinkshere-list')('li')
  17. urls = []
  18. # 获取网址
  19. for human in human_list:
  20. url = human.find('a')['href']
  21. urls.append('https://www.wikidata.org'+url)
  22. # 获取每个网页的name和description
  23. def parser(url):
  24. req = requests.get(url)
  25. # 利用BeautifulSoup将获取到的文本解析成HTML
  26. soup = BeautifulSoup(req.text, "lxml")
  27. # 获取name和description
  28. name = soup.find('span', class_="wikibase-title-label")
  29. desc = soup.find('span', class_="wikibase-descriptionview-text")
  30. if name is not None and desc is not None:
  31. print('%-40s,\t%s'%(name.text, desc.text))
  32. # 利用并发加速爬取
  33. executor = ThreadPoolExecutor(max_workers=20)
  34. # submit()的参数: 第一个为函数, 之后为该函数的传入参数,允许有多个
  35. future_tasks = [executor.submit(parser, url) for url in urls]
  36. # 等待所有的线程完成,才进入后续的执行
  37. wait(future_tasks, return_when=ALL_COMPLETED)
  38. t2 = time.time() # 结束时间
  39. print('并发方法,总共耗时:%s' % (t2 - t1))
  40. print('#' * 50)

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

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

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

异步方法

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

  1. import requests
  2. from bs4 import BeautifulSoup
  3. import time
  4. import aiohttp
  5. import asyncio
  6. # 开始时间
  7. t1 = time.time()
  8. print('#' * 50)
  9. url = "http://www.wikidata.org/w/index.php?title=Special:WhatLinksHere/Q5&limit=500&from=0"
  10. # 请求头部
  11. 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'}
  12. # 发送HTTP请求
  13. req = requests.get(url, headers=headers)
  14. # 解析网页
  15. soup = BeautifulSoup(req.text, "lxml")
  16. # 找到name和Description所在的记录
  17. human_list = soup.find(id='mw-whatlinkshere-list')('li')
  18. urls = []
  19. # 获取网址
  20. for human in human_list:
  21. url = human.find('a')['href']
  22. urls.append('https://www.wikidata.org'+url)
  23. # 异步HTTP请求
  24. async def fetch(session, url):
  25. async with session.get(url) as response:
  26. return await response.text()
  27. # 解析网页
  28. async def parser(html):
  29. # 利用BeautifulSoup将获取到的文本解析成HTML
  30. soup = BeautifulSoup(html, "lxml")
  31. # 获取name和description
  32. name = soup.find('span', class_="wikibase-title-label")
  33. desc = soup.find('span', class_="wikibase-descriptionview-text")
  34. if name is not None and desc is not None:
  35. print('%-40s,\t%s'%(name.text, desc.text))
  36. # 处理网页,获取name和description
  37. async def download(url):
  38. async with aiohttp.ClientSession() as session:
  39. try:
  40. html = await fetch(session, url)
  41. await parser(html)
  42. except Exception as err:
  43. print(err)
  44. # 利用asyncio模块进行异步IO处理
  45. loop = asyncio.get_event_loop()
  46. tasks = [asyncio.ensure_future(download(url)) for url in urls]
  47. tasks = asyncio.gather(*tasks)
  48. loop.run_until_complete(tasks)
  49. t2 = time.time() # 结束时间
  50. print('使用异步,总共耗时:%s' % (t2 - t1))
  51. print('#' * 50)

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

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

显然,异步方法使用了异步和并发两种提速方法,自然在速度有明显提升,大约为一般方法的六分之一。异步方法虽然效率高,但需要掌握异步编程,这需要学习一段时间。

关于异步方法与一般方法在速度上的比较,可以参考文章:利用aiohttp实现异步爬虫

如果有人觉得127秒的爬虫速度还是慢,可以尝试一下异步代码(与之前的异步代码的区别在于:仅仅使用了正则表达式代替BeautifulSoup来解析网页,以提取网页中的内容):

  1. import requests
  2. from bs4 import BeautifulSoup
  3. import time
  4. import aiohttp
  5. import asyncio
  6. import re
  7. # 开始时间
  8. t1 = time.time()
  9. print('#' * 50)
  10. url = "http://www.wikidata.org/w/index.php?title=Special:WhatLinksHere/Q5&limit=500&from=0"
  11. # 请求头部
  12. headers = {
  13. 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36'}
  14. # 发送HTTP请求
  15. req = requests.get(url, headers=headers)
  16. # 解析网页
  17. soup = BeautifulSoup(req.text, "lxml")
  18. # 找到name和Description所在的记录
  19. human_list = soup.find(id='mw-whatlinkshere-list')('li')
  20. urls = []
  21. # 获取网址
  22. for human in human_list:
  23. url = human.find('a')['href']
  24. urls.append('https://www.wikidata.org' + url)
  25. # 异步HTTP请求
  26. async def fetch(session, url):
  27. async with session.get(url) as response:
  28. return await response.text()
  29. # 解析网页
  30. async def parser(html):
  31. # 利用正则表达式解析网页
  32. try:
  33. name = re.findall(r'<span class="wikibase-title-label">(.+?)</span>', html)[0]
  34. desc = re.findall(r'<span class="wikibase-descriptionview-text">(.+?)</span>', html)[0]
  35. print('%-40s,\t%s' % (name, desc))
  36. except Exception as err:
  37. pass
  38. # 处理网页,获取name和description
  39. async def download(url):
  40. async with aiohttp.ClientSession() as session:
  41. try:
  42. html = await fetch(session, url)
  43. await parser(html)
  44. except Exception as err:
  45. print(err)
  46. # 利用asyncio模块进行异步IO处理
  47. loop = asyncio.get_event_loop()
  48. tasks = [asyncio.ensure_future(download(url)) for url in urls]
  49. tasks = asyncio.gather(*tasks)
  50. loop.run_until_complete(tasks)
  51. t2 = time.time() # 结束时间
  52. print('使用异步(正则表达式),总共耗时:%s' % (t2 - t1))
  53. print('#' * 50)

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

  1. ##################################################
  2. Dejen Gebremeskel , Ethiopian long-distance runner
  3. Erik Kynard , American high jumper
  4. ......
  5. Buzz Aldrin , American astronaut
  6. Egon Krenz , former General Secretary of the Socialist Unity Party of East Germany
  7. 使用异步(正则表达式),总共耗时:16.521944999694824
  8. ##################################################

16.5秒,仅仅为一般方法的43分之一,速度如此之快,令人咋舌(感谢某人提供的尝试)。笔者虽然自己实现了异步方法,但用的是BeautifulSoup来解析网页,耗时127秒,没想到使用正则表达式就取得了如此惊人的效果。可见,BeautifulSoup解析网页虽然快,但在异步方法中,还是限制了速度。但这种方法的缺点为,当你需要爬取的内容比较复杂时,一般的正则表达式就难以胜任了,需要另想办法。

爬虫框架Scrapy

最后,我们使用著名的Python爬虫框架Scrapy来解决这个爬虫。我们创建的爬虫项目为wikiDataScrapy,项目结构如下:

 

 

在settings.py中设置“ROBOTSTXT_OBEY = False”. 修改items.py,代码如下:

  1. # -*- coding: utf-8 -*-
  2. import scrapy
  3. class WikidatascrapyItem(scrapy.Item):
  4. # define the fields for your item here like:
  5. name = scrapy.Field()
  6. desc = scrapy.Field()

然后,在spiders文件夹下新建wikiSpider.py,代码如下:

  1. import scrapy.cmdline
  2. from wikiDataScrapy.items import WikidatascrapyItem
  3. import requests
  4. from bs4 import BeautifulSoup
  5. # 获取请求的500个网址,用requests+BeautifulSoup搞定
  6. def get_urls():
  7. url = "http://www.wikidata.org/w/index.php?title=Special:WhatLinksHere/Q5&limit=500&from=0"
  8. # 请求头部
  9. headers = {
  10. 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36'}
  11. # 发送HTTP请求
  12. req = requests.get(url, headers=headers)
  13. # 解析网页
  14. soup = BeautifulSoup(req.text, "lxml")
  15. # 找到name和Description所在的记录
  16. human_list = soup.find(id='mw-whatlinkshere-list')('li')
  17. urls = []
  18. # 获取网址
  19. for human in human_list:
  20. url = human.find('a')['href']
  21. urls.append('https://www.wikidata.org' + url)
  22. # print(urls)
  23. return urls
  24. # 使用scrapy框架爬取
  25. class bookSpider(scrapy.Spider):
  26. name = 'wikiScrapy' # 爬虫名称
  27. start_urls = get_urls() # 需要爬取的500个网址
  28. def parse(self, response):
  29. item = WikidatascrapyItem()
  30. # name and description
  31. item['name'] = response.css('span.wikibase-title-label').xpath('text()').extract_first()
  32. item['desc'] = response.css('span.wikibase-descriptionview-text').xpath('text()').extract_first()
  33. yield item
  34. # 执行该爬虫,并转化为csv文件
  35. scrapy.cmdline.execute(['scrapy', 'crawl', 'wikiScrapy', '-o', 'wiki.csv', '-t', 'csv'])

输出结果如下(只包含最后的Scrapy信息总结部分):

  1. {'downloader/request_bytes': 166187,
  2. 'downloader/request_count': 500,
  3. 'downloader/request_method_count/GET': 500,
  4. 'downloader/response_bytes': 18988798,
  5. 'downloader/response_count': 500,
  6. 'downloader/response_status_count/200': 500,
  7. 'finish_reason': 'finished',
  8. 'finish_time': datetime.datetime(2018, 10, 16, 9, 49, 15, 761487),
  9. 'item_scraped_count': 500,
  10. 'log_count/DEBUG': 1001,
  11. 'log_count/INFO': 8,
  12. 'response_received_count': 500,
  13. 'scheduler/dequeued': 500,
  14. 'scheduler/dequeued/memory': 500,
  15. 'scheduler/enqueued': 500,
  16. 'scheduler/enqueued/memory': 500,
  17. 'start_time': datetime.datetime(2018, 10, 16, 9, 48, 44, 58673)}

可以看到,已成功爬取500个网页,耗时31秒,速度也相当OK。再来看一下生成的wiki.csv文件,它包含了所有的输出的name和description,如下图:

 

 

可以看到,输出的CSV文件的列并不是有序的。至于如何解决Scrapy输出的CSV文件有换行的问题,请参考stackoverflow上的回答:https://stackoverflow.com/questions/39477662/scrapy-csv-file-has-uniform-empty-rows/43394566#43394566 。

Scrapy来制作爬虫的优势在于它是一个成熟的爬虫框架,支持异步,并发,容错性较好(比如本代码中就没有处理找不到name和description的情形),但如果需要频繁地修改中间件,则还是自己写个爬虫比较好,而且它在速度上没有超过我们自己写的异步爬虫,至于能自动导出CSV文件这个功能,还是相当实在的。

总结

本文内容较多,比较了4种爬虫方法,每种方法都有自己的利弊,已在之前的陈述中给出,当然,在实际的问题中,并不是用的工具或方法越高级就越好,具体问题具体分析嘛~
本文到此结束,感谢阅读哦~

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/运维做开发/article/detail/868491
推荐阅读
相关标签
  

闽ICP备14008679号