Scrapy之CrawlSpider

简介

	CrawlSpide r其实是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这个类的。

爬虫文件

# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule


class CrawlsSpider(CrawlSpider):
    name = 'crawls'
    # allowed_domains = ['www.xxx.com']
    start_urls = ['https://www.qiushibaike.com/text/']
    # 连接提取器: 可以根据指定规则进行连接的提取
    link = LinkExtractor(allow=r'/page/\d+/')   # allow: 提取连接规则->正则
    rules = (
        # 规则解析器: 根据规则进行响应数据的解析
        # follow: 将连接提取器继续作用到连接提取器提取出的连接所对应的页面源码中
        Rule(link, callback='parse_item', follow=True),
    )

    # 回调函数调用的次数是由连接提取器连接个数决定
    def parse_item(self, response):
        print(response)
1. CrawlSpider类和Spider类的最大不同是CrawlSpider多了一个rules属性,其作用是定义”提取动作“。在rules中可以包含一个或多个Rule对象,在Rule对象中包含了LinkExtractor对象。

2. LinkExtractor:顾名思义,链接提取器。
LinkExtractor(

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

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

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

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

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

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

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

Rule(LinkExtractor(allow=r'Items/'), callback='parse_item', follow=True)
- 参数介绍:
	参数1:指定链接提取器
	参数2:指定规则解析器解析数据的规则(回调函数)
	参数3:是否将链接提取器继续作用到链接提取器提取出的链接网页中。当callback为None,follow的默认值为true。
    
4. rules=( ):指定不同规则解析器。一个Rule对象表示一种提取规则。
    
5. CrawlSpider整体爬取流程:
	a)爬虫文件首先根据起始url,获取该url的网页内容
	b)链接提取器会根据指定提取规则将步骤a中网页内容中的链接进行提取
	c)规则解析器会根据指定解析规则将链接提取器中提取到的链接中的网页内容根据指定的规则进行解析
	d)将解析数据封装到item中,然后提交给管道进行持久化存储

示例

爬取boss直聘

# 爬虫文件
# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from BossPro.items import FirstItem, DescItem

class BossSpider(CrawlSpider):
    name = 'boss'
    # allowed_domains = ['www.xxx.com']
    start_urls = ['https://www.zhipin.com/c101010100/?...-prev']

    link = LinkExtractor(allow=r'python.*?page=\d+')
    link_detail = LinkExtractor(allow=r'job_detail/.*?.html')
    # rules元组中存放着不同的规则解析
    rules = (
        Rule(link, callback='parse_item', follow=True),
        Rule(link_detail, callback='parse_detail'),
    )

    def parse_item(self, response):
        li_list = response.xpath('//div[@class="job-list"]/ul/li')
        for li in li_list:
            item = FirstItem()
            title = li.xpath('./div/div[1]/h3/a/div/text()').extract_first()
            print(title)
            item['title'] = title
            yield item

    def parse_detail(self, response):
        desc_list = response.xpath('//div[@class="job-sec"]//text()').extract()
        item = DescItem()
        item['desc'] = "".join(desc_list)

        yield item
# items 文件
import scrapy

class FirstItem(scrapy.Item):
    # define the fields for your item here like:
    title = scrapy.Field()

class DescItem(scrapy.Item):
    # define the fields for your item here like:
    desc = scrapy.Field()
# pipelines(管道)文件
class BossproPipeline(object):
    f1 = None
    f2 = None

    def open_spider(self, spider):
        self.f1 = open('a.text', 'w', encoding='utf-8')
        self.f2 = open('b.text', 'w', encoding='utf-8')

    def process_item(self, item, spider):
        if item.__class__.__name__ == 'FirstItem':
            title = item['title']
            self.f1.write(title + '\n')
        else:
            title = item['desc']
            self.f2.write(title + '\n')
        return item

    def close_spider(self, spider):
        self.f1.close()
        self.f2.close()
# settings中注册管道
ITEM_PIPELINES = {
   'BossPro.pipelines.BossproPipeline': 300,
}
posted @ 2019-06-27 10:20  言值  阅读(124)  评论(0编辑  收藏  举报