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

阅读目录:

引入

提问:如果想要通过爬虫程序去爬取”糗百“全站数据新闻数据的话,有几种实现方法?

  • 方法一:基于Scrapy框架中的Spider的递归爬取进行实现(Request模块递归回调parse方法)。
  • 方法二:基于CrawlSpider的自动爬取进行实现(更加简洁和高效)。

CrawlSpider简介

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

CrawlSpider使用

    • 基于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
#导入CrawlSpider相关模块
from scrapy.linkextractors import LinkExtractor   #导入链接提取器
from scrapy.spiders import CrawlSpider, Rule      #导入规则提取器


class CrawlproSpider(CrawlSpider):  #继承CrawlSpider类
    name = 'crawlpro'
    allowed_domains = ['www.12.com']
    start_urls = ['http://www.12.com/']
    
    #提取link规则
    rules = (
        Rule(LinkExtractor(allow=r'Items/'), callback='parse_item', follow=True),
    )
 
    #解析方法
    def parse_item(self, response):
        item = {}
        #item['domain_id'] = response.xpath('//input[@id="sid"]/@value').get()
        #item['name'] = response.xpath('//div[@id="name"]').get()
        #item['description'] = response.xpath('//div[@id="description"]').get()
        return item

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中,然后提交给管道进行持久化存储

 示范案例:爬取boss直聘网站的岗位名称,及其详情页的岗位职责描述

爬虫文件:

# -*- coding: utf-8 -*-
import scrapy

from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from  ..items import DetailItem,FirstItem
#爬取的是岗位名称(首页)和岗位描述(详情页)
class CrawlproSpider(CrawlSpider):
    name = 'crawlpro'
    # allowed_domains = ['www.12.com']
    start_urls = ['https://www.zhipin.com/c101010100/?query=python%E5%BC%80%E5%8F%91&page=1&ka=page-prev']
    link = LinkExtractor(allow=r'page=\d+')
    link_detail = LinkExtractor(allow=r'/job_detail/.*?html')
    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()
            job_title = li.xpath('.//div[@class="job-title"]/text()').extract_first()
            item['job_title'] = job_title
            yield item

    def parse_detail(self, response):
        job_desc = response.xpath('//*[@id="main"]/div[3]/div/div[2]/div[2]/div[1]/div//text()').extract()
        item = DetailItem()
        job_desc = ''.join(job_desc)
        item['job_desc'] = job_desc
        yield item
爬虫文件

items文件:

# -*- 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 DetailItem(scrapy.Item):
    # define the fields for your item here like:
    job_desc = scrapy.Field()
class FirstItem(scrapy.Item):
    # define the fields for your item here like:
    job_title = scrapy.Field()
items.py

管道文件:

# -*- 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 BossproPipeline(object):
    f1,f2 = None,None
    def open_spider(self,spider):
        self.f1 = open('a.txt','w',encoding='utf-8')
        self.f2 = open('b.txt', 'w', encoding='utf-8')
    def process_item(self, item, spider):

        #item在同一时刻只可以接收到某一个指定item对象
        if item.__class__.__name__ == 'FirstItem':
            job_title = item['job_title']
            self.f1.write(job_title+'\n')
        else:
            job_desc = item['job_desc']
            self.f2.write(job_desc)
        return item
pipelines.py

配置文件:

ITEM_PIPELINES = {
   'CrawlPro.pipelines.BossproPipeline': 300,
}

最终实现:

 

posted @ 2019-05-09 23:36  小萍瓶盖儿  阅读(178)  评论(0编辑  收藏  举报