一.简介

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

二.使用

  1.创建scrapy工程:scrapy startproject projectName

  2.创建爬虫文件:scrapy genspider -t crawl spiderName www.xxx.com

    --此指令对比以前的指令多了 "-t crawl",表示创建的爬虫文件是基于CrawlSpider这个类的,而不再是Spider这个基类。

  3.观察生成的爬虫文件

  1. # -*- coding: utf-8 -*-
  2. import scrapy
  3. from scrapy.linkextractors import LinkExtractor
  4. from scrapy.spiders import CrawlSpider, Rule
  5.  
  6. class ChoutidemoSpider(CrawlSpider):
  7. name = 'choutiDemo'
  8. #allowed_domains = ['www.chouti.com']
  9. start_urls = ['http://www.chouti.com/']
  10.  
  11. rules = (
  12. Rule(LinkExtractor(allow=r'Items/'), callback='parse_item', follow=True),
  13. )
  14.  
  15. def parse_item(self, response):
  16. i = {}
  17. #i['domain_id'] = response.xpath('//input[@id="sid"]/@value').extract()
  18. #i['name'] = response.xpath('//div[@id="name"]').extract()
  19. #i['description'] = response.xpath('//div[@id="description"]').extract()
  20. return i

- 2,3行:导入CrawlSpider相关模块

  - 7行:表示该爬虫程序是基于CrawlSpider类的

  - 12,13,14行:表示为提取Link规则

  - 16行:解析方法

  CrawlSpider类和Spider类的最大不同是CrawlSpider多了一个rules属性,其作用是定义”提取动作“。在rules中可以包含一个或多个Rule对象,在Rule对象中包含了LinkExtractor对象。

3.1 LinkExtractor:顾名思义,链接提取器。

    LinkExtractor(

         allow=r'Items/',# 满足括号中“正则表达式”的值会被提取,如果为空,则全部匹配。

         deny=xxx,  # 满足正则表达式的则不会被提取。

         restrict_xpaths=xxx, # 满足xpath表达式的值会被提取

         restrict_css=xxx, # 满足css表达式的值会被提取

         deny_domains=xxx, # 不会被提取的链接的domains。 

  1.    )

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

    

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

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

    - 参数介绍:

      参数1:指定链接提取器

      参数2:指定规则解析器解析数据的规则(回调函数)

      参数3:是否将链接提取器继续作用到链接提取器提取出的链接网页中。当callback为None,参数3的默认值为true。

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

  3.4 CrawlSpider整体爬取流程:

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

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

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

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

  4.简单代码实战应用

4.1 爬取糗事百科糗图板块的所有页码数据

  1. # -*- coding: utf-8 -*-
  2. import scrapy
  3. from scrapy.linkextractors import LinkExtractor
  4. from scrapy.spiders import CrawlSpider, Rule
  5.  
  6. class CrawldemoSpider(CrawlSpider):
  7. name = 'qiubai'
  8. #allowed_domains = ['www.qiushibaike.com']
  9. start_urls = ['https://www.qiushibaike.com/pic/']
  10.  
  11. #连接提取器:会去起始url响应回来的页面中提取指定的url
  12. link = LinkExtractor(allow=r'/pic/page/\d+\?') #s=为随机数
  13. link1 = LinkExtractor(allow=r'/pic/$')#爬取第一页
  14. #rules元组中存放的是不同的规则解析器(封装好了某种解析规则)
  15. rules = (
  16. #规则解析器:可以将连接提取器提取到的所有连接表示的页面进行指定规则(回调函数)的解析
  17. Rule(link, callback='parse_item', follow=True),
  18. Rule(link1, callback='parse_item', follow=True),
  19. )
  20.  
  21. def parse_item(self, response):
  22. print(response)

  4.2 爬虫文件:

  1. # -*- coding: utf-8 -*-
  2. import scrapy
  3. from scrapy.linkextractors import LinkExtractor
  4. from scrapy.spiders import CrawlSpider, Rule
  5. from qiubaiBycrawl.items import QiubaibycrawlItem
  6. import re
  7. class QiubaitestSpider(CrawlSpider):
  8. name = 'qiubaiTest'
  9. #起始url
  10. start_urls = ['http://www.qiushibaike.com/']
  11.  
  12. #定义链接提取器,且指定其提取规则
  13. page_link = LinkExtractor(allow=r'/8hr/page/\d+/')
  14.  
  15. rules = (
  16. #定义规则解析器,且指定解析规则通过callback回调函数
  17. Rule(page_link, callback='parse_item', follow=True),
  18. )
  19.  
  20. #自定义规则解析器的解析规则函数
  21. def parse_item(self, response):
  22. div_list = response.xpath('//div[@id="content-left"]/div')
  23.  
  24. for div in div_list:
  25. #定义item
  26. item = QiubaibycrawlItem()
  27. #根据xpath表达式提取糗百中段子的作者
  28. item['author'] = div.xpath('./div/a[2]/h2/text()').extract_first().strip('\n')
  29. #根据xpath表达式提取糗百中段子的内容
  30. item['content'] = div.xpath('.//div[@class="content"]/span/text()').extract_first().strip('\n')
  31.  
  32. yield item #将item提交至管道

  4.3 item文件:

  1. # -*- coding: utf-8 -*-
  2.  
  3. # Define here the models for your scraped items
  4. #
  5. # See documentation in:
  6. # https://doc.scrapy.org/en/latest/topics/items.html
  7.  
  8. import scrapy
  9.  
  10. class QiubaibycrawlItem(scrapy.Item):
  11. # define the fields for your item here like:
  12. # name = scrapy.Field()
  13. author = scrapy.Field() #作者
  14. content = scrapy.Field() #内容

  4.4 管道文件:

  1. # -*- coding: utf-8 -*-
  2.  
  3. # Define your item pipelines here
  4. #
  5. # Don't forget to add your pipeline to the ITEM_PIPELINES setting
  6. # See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
  7.  
  8. class QiubaibycrawlPipeline(object):
  9.  
  10. def __init__(self):
  11. self.fp = None
  12.  
  13. def open_spider(self,spider):
  14. print('开始爬虫')
  15. self.fp = open('./data.txt','w')
  16.  
  17. def process_item(self, item, spider):
  18. #将爬虫文件提交的item写入文件进行持久化存储
  19. self.fp.write(item['author']+':'+item['content']+'\n')
  20. return item
  21.  
  22. def close_spider(self,spider):
  23. print('结束爬虫')
  24. self.fp.close()

15 Scrapy框架之CrawlSpider的更多相关文章

  1. 爬虫scrapy框架之CrawlSpider

    爬虫scrapy框架之CrawlSpider   引入 提问:如果想要通过爬虫程序去爬取全站数据的话,有几种实现方法? 方法一:基于Scrapy框架中的Spider的递归爬取进行实现(Request模 ...

  2. Python网络爬虫之Scrapy框架(CrawlSpider)

    目录 Python网络爬虫之Scrapy框架(CrawlSpider) CrawlSpider使用 爬取糗事百科糗图板块的所有页码数据 Python网络爬虫之Scrapy框架(CrawlSpider) ...

  3. Scrapy框架之CrawlSpider

    提问:如果想要通过爬虫程序去爬取”糗百“全站数据新闻数据的话,有几种实现方法? 方法一:基于Scrapy框架中的Spider的递归爬取进行实现(Request模块递归回调parse方法). 方法二:基 ...

  4. 16.Python网络爬虫之Scrapy框架(CrawlSpider)

    引入 提问:如果想要通过爬虫程序去爬取”糗百“全站数据新闻数据的话,有几种实现方法? 方法一:基于Scrapy框架中的Spider的递归爬取进行实现(Request模块递归回调parse方法). 方法 ...

  5. scrapy框架之CrawlSpider操作

    提问:如果想要通过爬虫程序去爬取”糗百“全站数据新闻数据的话,有几种实现方法? 方法一:基于Scrapy框架中的Spider的递归爬取进行实现(Request模块递归回调parse方法). 方法二:基 ...

  6. 爬虫开发11.scrapy框架之CrawlSpider操作

    提问:如果想要通过爬虫程序去爬取”糗百“全站数据新闻数据的话,有几种实现方法? 方法一:基于Scrapy框架中的Spider的递归爬取进行实现(Request模块递归回调parse方法). 方法二:基 ...

  7. scrapy框架基于CrawlSpider的全站数据爬取

    引入 提问:如果想要通过爬虫程序去爬取”糗百“全站数据新闻数据的话,有几种实现方法? 方法一:基于Scrapy框架中的Spider的递归爬取进行实现(Request模块递归回调parse方法). 方法 ...

  8. scrapy框架之(CrawlSpider)

    一.CrawlSpider简介 如果想要通过爬虫程序去爬取”糗百“全站数据新闻数据的话,有几种实现方法? 方法一:基于Scrapy框架中的Spider的递归爬取进行实现(Request模块递归回调pa ...

  9. 16,Python网络爬虫之Scrapy框架(CrawlSpider)

    今日概要 CrawlSpider简介 CrawlSpider使用 基于CrawlSpider爬虫文件的创建 链接提取器 规则解析器 引入 提问:如果想要通过爬虫程序去爬取”糗百“全站数据新闻数据的话, ...

随机推荐

  1. 测试linux服务器是否能接入微信

    官方文档:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421135319 php.代码 <?php $a = $_GE ...

  2. CentOS7——卡在在启动界面

    系统在启动时,卡在启动界面比如: 解决方法一 这个时候其实系统已经启动了,如果这台机器之前正确配置好了网络连接的话,此时我们可以使用另外一台机器通过SSH来登录这台机器进行修改. 这个时候将系统出问题 ...

  3. CentOS7 yum install elasticsearch

    首先安装 JDK 环境 # 本机是否已经安装,ElasticSearch 最低支持 jdk 1.7 yum list installed | grep java # 查看 yum 库中的 java 安 ...

  4. 6.HBase时髦谨慎财会会计

    1.基本概念和原理 2.核心知识点 3.安装部署 4.Hbase开发

  5. Simple Cel Shading 钟馗

    Made with Unity Unannouced project Character Art by Chris P

  6. javascript 生成img标签的3种方式(对象、方法、html)

    <div id="d1"></div> <script> //HTML function a(){ document.getElementByI ...

  7. Redis常见报错之 Redis::CommandError (MISCONF Redis is configured to save RDB snapshots, but it is currently not able to persist on disk)

    在Redis运行过程中,报错信息如下: Redis::CommandError (MISCONF Redis is configured to save RDB snapshots, but it i ...

  8. 七十五:flask.Restful之Restful.API介绍

    restful api是用于在前端与后台进行通信的一套规范,使用这个规范可以让前后端开发变得更加轻松 协议:http或者https 数据传输格式:使用json url链接:url链接中不能有动词(/g ...

  9. 初探ASP.NET Web API (转)

    http://www.cnblogs.com/mejoy/p/6402821.html 什么是ASP.NET Web API? 官方的解释是 ASP.NET Web API is a framewor ...

  10. java8:(Lambda 表达式,Supplier,@FunctionalInterface,foreach(),Optional,Stream().collect,双冒号,joining,partitioningBy分区,collectingAndThen,filter())

    1.Lambda 表达式: 引导:http://www.cnblogs.com/yulinfeng/p/8452379.html DEMO1: List<String> names1 = ...