5 CrawlSpider操作
CrawlSpider
提问:如果想要通过爬虫程序去爬取”糗百“全站数据新闻数据的话,有几种实现方法?
方法一:基于Scrapy框架中的Spider的递归爬取进行实现(Request模块递归回调parse方法)。
方法二:基于CrawlSpider的自动爬取进行实现(更加简洁和高效)。
CrawlSpider
一.简介
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.观察生成的爬虫文件
# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule class ChoutidemoSpider(CrawlSpider):
name = 'choutiDemo'
#allowed_domains = ['www.chouti.com']
start_urls = ['http://www.chouti.com/'] rules = (
Rule(LinkExtractor(allow=r'Items/'), callback='parse_item', follow=True),
) def parse_item(self, response):
i = {}
#i['domain_id'] = response.xpath('//input[@id="sid"]/@value').extract()
#i['name'] = response.xpath('//div[@id="name"]').extract()
#i['description'] = response.xpath('//div[@id="description"]').extract()
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。
)
- 作用:提取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 爬虫文件:


# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from qiubaiBycrawl.items import QiubaibycrawlItem
import re
class QiubaitestSpider(CrawlSpider):
name = 'qiubaiTest'
#起始url
start_urls = ['http://www.qiushibaike.com/'] #定义链接提取器,且指定其提取规则
page_link = LinkExtractor(allow=r'/8hr/page/\d+/') rules = (
#定义规则解析器,且指定解析规则通过callback回调函数
Rule(page_link, callback='parse_item', follow=True),
) #自定义规则解析器的解析规则函数
def parse_item(self, response):
div_list = response.xpath('//div[@id="content-left"]/div') for div in div_list:
#定义item
item = QiubaibycrawlItem()
#根据xpath表达式提取糗百中段子的作者
item['author'] = div.xpath('./div/a[2]/h2/text()').extract_first().strip('\n')
#根据xpath表达式提取糗百中段子的内容
item['content'] = div.xpath('.//div[@class="content"]/span/text()').extract_first().strip('\n') yield item #将item提交至管道
view
4.2 item文件:


# -*- coding: utf-8 -*- # Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html import scrapy class QiubaibycrawlItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
author = scrapy.Field() #作者
content = scrapy.Field() #内容
view
4.3 管道文件:


# -*- coding: utf-8 -*- # Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html class QiubaibycrawlPipeline(object): def __init__(self):
self.fp = None def open_spider(self,spider):
print('开始爬虫')
self.fp = open('./data.txt','w') def process_item(self, item, spider):
#将爬虫文件提交的item写入文件进行持久化存储
self.fp.write(item['author']+':'+item['content']+'\n')
return item def close_spider(self,spider):
print('结束爬虫')
self.fp.close()
view
5 CrawlSpider操作的更多相关文章
- scrapy框架之CrawlSpider操作
提问:如果想要通过爬虫程序去爬取”糗百“全站数据新闻数据的话,有几种实现方法? 方法一:基于Scrapy框架中的Spider的递归爬取进行实现(Request模块递归回调parse方法). 方法二:基 ...
- 爬虫开发11.scrapy框架之CrawlSpider操作
提问:如果想要通过爬虫程序去爬取”糗百“全站数据新闻数据的话,有几种实现方法? 方法一:基于Scrapy框架中的Spider的递归爬取进行实现(Request模块递归回调parse方法). 方法二:基 ...
- 爬虫学习-使用CrawlSpider
使用scrapy中的CrawlSpider类来进行爬行 一直用的是BaseSpider,回调函数的方式,有一个问题是title,date在一个页面,author,detail在另一个页面时,怎么把这些 ...
- 【python 网络爬虫】之scrapy系列
网络爬虫之scripy系列 [scrapy网络爬虫]之0 爬虫与反扒 [scrapy网络爬虫]之一 scrapy框架简介和基础应用 [scrapy网络爬虫]之二 持久化操作 [scrapy网络爬虫]之 ...
- python爬虫入门(八)Scrapy框架之CrawlSpider类
CrawlSpider类 通过下面的命令可以快速创建 CrawlSpider模板 的代码: scrapy genspider -t crawl tencent tencent.com CrawSpid ...
- 爬虫框架之Scrapy(三 CrawlSpider)
如何爬取一个网站的全站数据? 可以使用Scrapy中基于Spider的递归方式进行爬取(Request模块回调parse方法) 还有一种更高效的方法,就是基于CrawlSpider的自动爬取实现 简介 ...
- Scrapy框架-CrawlSpider
目录 1.CrawlSpider介绍 2.CrawlSpider源代码 3. LinkExtractors:提取Response中的链接 4. Rules 5.重写Tencent爬虫 6. Spide ...
- crawlspider
Scrapy中CrawSpider 回头看: 之前的代码中,我们有很大一部分时间在寻找下一页的url地址或者是内容的url地址或者是内容的url地址上面,这个过程能更简单一些么? 思路: 1. 从re ...
- CrawlSpider模板
crawlSpider 创建CrawlSpider模板 scrapy genspider -t crawl <爬虫名字> <域名> 模板代码示例: # -*- coding: ...
随机推荐
- ambassador 学习七 Mapping说明
mapping 通过rest 资源与k8s 的service进行关联,ambassador 必须有一个或者多个提供访问servide 的mapping定义 mapping 可以包含的配置 rewrit ...
- 完全卸载vs2013、vs2015的方法
Visual Studio安装过程会安装好多组件,如果想要卸载的话会出现一些因难,在控制面板不容易卸载干净,在Linux下的命令都有--help参数来显示命令的用法,今天突发奇想,在控制台下输入vs2 ...
- Android中Parcelable与Serializable接口用法
转自: Android中Parcelable接口用法 1. Parcelable接口 Interface for classes whose instances can be written to a ...
- C++实现大正整数及其相关运算(长期更新)
/** 只考虑正数[1, +∞); “-”运算只允许大数减小数; 小端存储: */ typedef struct BigInteger0 { vector<int> v; BigInteg ...
- mysql修复表
数据库Table xxx is marked as crashed and should be repaired错误的解决方法服务器断电等原因可能导致数据表损坏,导致访问的时候提示:Table xxx ...
- 5_bootstrap之响应式布局|列表|按钮
5.响应式工具 为针对性地在移动页面上展示和隐藏不同的内容,bootStrap提供响应式工具. 可以让开发人员通过该工具决定,在何种屏幕尺寸下,隐藏或者显示某些元素 帮助手册位置:全局CSS样式--- ...
- params over length limit is 20
- Jenkins是什么?
Jenkins 是一个可扩展的持续集成引擎. 主要用于: l 持续.自动地构建/测试软件项目. l 监控一些定时执行的任务. Jenkins拥有的特性包括: l 易于安装-只要把jenkins.war ...
- IntelliJ Idea 常用快捷键列表 (需整理下) https://blog.csdn.net/dc_726/article/details/42784275
[常规] https://blog.csdn.net/dc_726/article/details/42784275https://jingyan.baidu.com/article/59a015e3 ...
- Drools5
参考:https://wenku.baidu.com/view/a6516373f242336c1eb95e7c.html (比较好的 但是是drl 原生的) 参考2:http://asialee ...