Scrapy CrawlSpider介绍和使用

た 入场券 2023-10-10 21:36 165阅读 0赞

一、介绍CrawlSpider

  CrawlSpider其实是Spider的一个子类,除了继承到Spider的特性和功能外,还派生除了其自己独有的更加强大的特性和功能。其中最显著的功能就是”LinkExtractors链接提取器“。Spider是所有爬虫的基类,其设计原则只是为了爬取start_url列表中网页,而从爬取到的网页中提取出的url进行继续的爬取工作使用CrawlSpider更合适。

83e8b227d7704ab2bc72556decb1e00b.png

源码:

  1. class CrawlSpider(Spider):
  2. rules = ()
  3. def __init__(self, *a, **kw):
  4. super(CrawlSpider, self).__init__(*a, **kw)
  5. self._compile_rules()
  6. #首先调用parse()来处理start_urls中返回的response对象
  7. #parse()则将这些response对象传递给了_parse_response()函数处理,并设置回调函数为parse_start_url()
  8. #设置了跟进标志位True
  9. #parse将返回item和跟进了的Request对象
  10. def parse(self, response):
  11. return self._parse_response(response, self.parse_start_url, cb_kwargs={}, follow=True)
  12. #处理start_url中返回的response,需要重写
  13. def parse_start_url(self, response):
  14. return []
  15. def process_results(self, response, results):
  16. return results
  17. #从response中抽取符合任一用户定义'规则'的链接,并构造成Resquest对象返回
  18. def _requests_to_follow(self, response):
  19. if not isinstance(response, HtmlResponse):
  20. return
  21. seen = set()
  22. #抽取之内的所有链接,只要通过任意一个'规则',即表示合法
  23. for n, rule in enumerate(self._rules):
  24. links = [l for l in rule.link_extractor.extract_links(response) if l not in seen]
  25. #使用用户指定的process_links处理每个连接
  26. if links and rule.process_links:
  27. links = rule.process_links(links)
  28. #将链接加入seen集合,为每个链接生成Request对象,并设置回调函数为_repsonse_downloaded()
  29. for link in links:
  30. seen.add(link)
  31. #构造Request对象,并将Rule规则中定义的回调函数作为这个Request对象的回调函数
  32. r = Request(url=link.url, callback=self._response_downloaded)
  33. r.meta.update(rule=n, link_text=link.text)
  34. #对每个Request调用process_request()函数。该函数默认为indentify,即不做任何处理,直接返回该Request.
  35. yield rule.process_request(r)
  36. #处理通过rule提取出的连接,并返回item以及request
  37. def _response_downloaded(self, response):
  38. rule = self._rules[response.meta['rule']]
  39. return self._parse_response(response, rule.callback, rule.cb_kwargs, rule.follow)
  40. #解析response对象,会用callback解析处理他,并返回request或Item对象
  41. def _parse_response(self, response, callback, cb_kwargs, follow=True):
  42. #首先判断是否设置了回调函数。(该回调函数可能是rule中的解析函数,也可能是 parse_start_url函数)
  43. #如果设置了回调函数(parse_start_url()),那么首先用parse_start_url()处理response对象,
  44. #然后再交给process_results处理。返回cb_res的一个列表
  45. if callback:
  46. #如果是parse调用的,则会解析成Request对象
  47. #如果是rule callback,则会解析成Item
  48. cb_res = callback(response, **cb_kwargs) or ()
  49. cb_res = self.process_results(response, cb_res)
  50. for requests_or_item in iterate_spider_output(cb_res):
  51. yield requests_or_item
  52. #如果需要跟进,那么使用定义的Rule规则提取并返回这些Request对象
  53. if follow and self._follow_links:
  54. #返回每个Request对象
  55. for request_or_item in self._requests_to_follow(response):
  56. yield request_or_item
  57. def _compile_rules(self):
  58. def get_method(method):
  59. if callable(method):
  60. return method
  61. elif isinstance(method, basestring):
  62. return getattr(self, method, None)
  63. self._rules = [copy.copy(r) for r in self.rules]
  64. for rule in self._rules:
  65. rule.callback = get_method(rule.callback)
  66. rule.process_links = get_method(rule.process_links)
  67. rule.process_request = get_method(rule.process_request)
  68. def set_crawler(self, crawler):
  69. super(CrawlSpider, self).set_crawler(crawler)
  70. self._follow_links = crawler.settings.getbool('CRAWLSPIDER_FOLLOW_LINKS', True)

文档:Spiders — Scrapy 2.9.0 documentation

二、框架搭建

  1. 1.创建scrapy框架工程
  2. scrapy startproject Meitou
  3. 2.进入工程目录
  4. cd Meitou
  5. 3.创建爬虫文件
  6. scrapy genspider -t crawl 爬虫任务名称 爬取的范围域
  7. scrapy genspider -t crawl crawl_yjin xx.com
  8. 此指令对比以前指令多了"-t crawl",表示创建的爬虫文件是基于CrawlSpider这个类的,而不再是Spider这个基类。
  9. 4.启动爬虫文件
  10. scrapy crawl crawl_yjin --nolog

(一)、查看生成的爬虫文件 :

36c2c883dbce43ccb4a10d9b91f30dc0.png

Rule(规则): 规范url构造请求对象的规则

LinkExtractor(链接提取器):规范url的提取范围

CrawlSpider:是一个类模板,继承自Spider,功能就更加的强大

(二)、查看LinkExtractor源码:

LinkExtractor 链接提取器

作用:提取response中符合规则的链接。

768afb428f4e4b1d95606f4175b00886.png

主要参数含义:

  1. LinkExtractor:规范url提取可用的部分
  2. allow=(): 满足括号中“正则表达式”的值会被提取,如果为空,则全部匹配。
  3. deny=(): 与这个正则表达式(或正则表达式列表)不匹配的URL一定不提取。
  4. allow_domains=():允许的范围域
  5. deny_domains=(): 不允许的范围域
  6. restrict_xpaths=(): 使用xpath表达式,和allow共同作用过滤链接(只选到节点,不选到属性)
  7. tags=('a', 'area'): 指定标签
  8. attrs=('href',): 指定属性

(三)、查看Rule源码:

Rule : 规则解析器。根据链接提取器中提取到的链接,根据指定规则提取解析器链接网页中的内容

Rule (LinkExtractor(allow=r”Items/“), callback=”parse_item”, follow=True)

b9d5352998dc4b4fb368104a09e6f5c7.png 主要参数含义:

  • - link_extractor为LinkExtractor,用于定义需要提取的链接
  • - callback参数:当link_extractor获取到链接时参数所指定的值作为回调函数
  • - callback参数使用注意: 当编写爬虫规则时,请避免使用parse作为回调函数。于CrawlSpider使用parse方法来实现其逻辑,如果您覆盖了parse方法,crawlspider将会运行失败
  • - follow:指定了根据该规则从response提取的链接是否需要跟进。 当callback为None,默认值为True
  • - process_links:主要用来过滤由link_extractor获取到的链接
  • - process_request:主要用来过滤在rule中提取到的request

rules=( ):指定不同规则解析器。一个Rule对象表示一种提取规则。

(四)、CrawlSpider整体爬取流程:

 (a) 爬虫文件首先根据起始url,获取该url的网页内容

 (b) 链接提取器会根据指定提取规则将步骤a中网页内容中的链接进行提取

 (c) 规则解析器会根据指定解析规则将链接提取器中提取到的链接中的网页内容根据指定的规则进行解析

 (d) 将解析数据封装到item中,然后提交给管道进行持久化存储

三、基于CrawlSpider使用

(1)spider爬虫文件代码

  1. import scrapy
  2. from scrapy.linkextractors import LinkExtractor
  3. from scrapy.spiders import CrawlSpider, Rule
  4. class CrawlYjinSpider(CrawlSpider):
  5. name = "crawl_yjin"
  6. allowed_domains = ["xiachufang.com"]
  7. start_urls = ["https://www.xiachufang.com/category/40073/"] # 起始url (分类列表的小吃)
  8. # 创建一个Rule对象(也创建一个LinkExtractor对象)
  9. rules = (
  10. # 菜单详情地址
  11. # https://www.xiachufang.com/recipe/106909278/
  12. # https://www.xiachufang.com/recipe/1055105/
  13. Rule(LinkExtractor(allow=r".*?/recipe/\d+/$"), callback="parse_item", follow=False),
  14. )
  15. # 解析菜单详情
  16. def parse_item(self, response):
  17. # 不需要手动构造item对象
  18. item = {}
  19. # print(response.url)
  20. # 图片链接,名称,评分,多少人做过,发布人
  21. item['imgs'] = response.xpath('//div/img/@src').get()
  22. #去除空格和\n
  23. item['title']=''.join(response.xpath('//div/h1/text()').get()).replace(' ','').replace('\n','')
  24. item['score']=response.xpath('//div[@class="score float-left"]/span[@class="number"]/text()').extract_first()
  25. item['number']=response.xpath('//div[@class="cooked float-left"]/span[@class="number"]/text()').get()
  26. item['author']=''.join(response.xpath('//div[@class="author"]/a/img/@alt').get()).replace('的厨房','')
  27. # print(item)
  28. return item

(2)数据保存>>pipelines管道文件

  1. import json
  2. from itemadapter import ItemAdapter
  3. class MeitouPipeline:
  4. """处理items对象的数据"""
  5. def __init__(self):
  6. self.file_=open('xcf-1.json','w',encoding='utf-8')
  7. print('文件打开了。。。')
  8. def process_item(self, item, spider):
  9. """item接收爬虫器丢过来的items对象"""
  10. py_dict=dict(item) # 先把携带键值对数据items对象转成字典
  11. #dict转换成json数据
  12. json_data=json.dumps(py_dict,ensure_ascii=False)+",\n"
  13. #写入
  14. self.file_.write(json_data)
  15. print("写入数据...")
  16. return item
  17. def __del__(self):
  18. self.file_.close() #关闭
  19. print('文件关闭了....')

(3) settings相关设置 >>settings.py设置文件

  1. # 全局用户代理,默认是被注释了,不生效
  2. USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36'
  3. # Obey robots.txt rules
  4. ROBOTSTXT_OBEY = False
  5. # 设置下载延时
  6. DOWNLOAD_DELAY = 1
  7. #开启管道
  8. ITEM_PIPELINES = {
  9. "Meitou.pipelines.MeitouPipeline": 300,
  10. }

(4)运行程序 >>scrapy crawl crawl_yjin —nolog
86fb9a0b77af4ffcb6c38d8bf7bcb537.png

查看保存的json文件

50c7396a1dd743d2b009d06cf50dd665.png

发表评论

表情:
评论列表 (有 0 条评论,165人围观)

还没有评论,来说两句吧...

相关阅读