CrawlSpider

CrawlSpider

简介

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

使用
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 
LinkExtractor
连接提取器 LinkExtractor( allow=r'Items/'# 知足括号中“正则表达式”的值会被提取,若是为空,则所有匹配。   deny=xxx, # 知足正则表达式的则不会被提取。 restrict_xpaths=xxx, # 知足xpath表达式的值会被提取   restrict_css=xxx,#知足css表达式的值会被提取   deny_domains=xxx,#不会被提取的连接的domains。     )     - 做用:提取response中符合规则的连接。 
Rule
规则解析器 Rule(LinkExtractor(allow=r'Items/'), callback='parse_item', follow=True)   - 参数介绍:     参数1:指定连接提取器     参数2:指定规则解析器解析数据的规则(回调函数)     参数3:是否将连接提取器继续做用到连接提取器提取出的连接网页中。当callbackNone,参数3的默认值为true
rules=( )
指定不一样规则解析器。一个Rule对象表示一种提取规则。 
CrawlSpider总体爬取流程
a)爬虫文件首先根据起始url,获取该url的网页内容 b)连接提取器会根据指定提取规则将步骤a中网页内容中的连接进行提取 c)规则解析器会根据指定解析规则将连接提取器中提取到的连接中的网页内容根据指定的规则进行解析 d)将解析数据封装到item中,而后提交给管道进行持久化存储
爬虫文件
# -*- 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提交至管道 

其余文件与以前的相同正则表达式

相关文章
相关标签/搜索