zoukankan      html  css  js  c++  java
  • scrapy框架基于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.观察生成的爬虫文件

    from scrapy.linkextractors import LinkExtractor
    from scrapy.spiders import CrawlSpider, Rule
    
    
    class CrawSpider(CrawlSpider):
        name = 'craw'
        allowed_domains = ['www.xxx.com']
        start_urls = ['http://www.xxx.com/']
    
        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

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

    三、简单代码实战应用

    爬取抽屉新热榜所有页码的数据

    # -*- coding: utf-8 -*-
    import scrapy
    from scrapy.linkextractors import LinkExtractor
    from scrapy.spiders import CrawlSpider, Rule
    
    
    class CrawSpider(CrawlSpider):
        name = 'craw'
        # allowed_domains = ['www.xxx.com']
        start_urls = ['https://dig.chouti.com/r/scoff/hot/1']
    
        # 连接提取器: 可以根据指定条件提取连接 正则
        link = LinkExtractor(allow=r'/r/scoff/hot/d+')
    
        # 规则解析器:将连接提取器提取到的连接对应的页面进行指定规则的数据解析
        rules = (
            Rule(link, callback='parse_item', follow=True),
            # 参数follow=True:将连接提取器继续作用到连接提取器提取到的连接所有对应的页面中,循环调用
        )
    
        def parse_item(self, response):
            # item = {}
            print(response)
            """
            ...
            <200 https://dig.chouti.com/r/scoff/hot/60>
            <200 https://dig.chouti.com/r/scoff/hot/57>
            <200 https://dig.chouti.com/r/scoff/hot/58>
             ...
            <200 https://dig.chouti.com/r/scoff/hot/119>
            <200 https://dig.chouti.com/r/scoff/hot/120>
            """
            #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

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

    第一页的url不同于其它页url,

    需要用到多个连接提取器、规则解析器
    # -*- coding: utf-8 -*-
    import scrapy
    from scrapy.linkextractors import LinkExtractor
    from scrapy.spiders import CrawlSpider, Rule
    
    
    class CrawldemoSpider(CrawlSpider):
        name = 'qiubai'
        #allowed_domains = ['www.qiushibaike.com']
        start_urls = ['https://www.qiushibaike.com/pic/']
    
        #连接提取器:会去起始url响应回来的页面中提取指定的url
        link = LinkExtractor(allow=r'/pic/page/d+?') #s=为随机数
        link1 = LinkExtractor(allow=r'/pic/$')#爬取第一页
        #rules元组中存放的是不同的规则解析器(封装好了某种解析规则)
        rules = (
            #规则解析器:可以将连接提取器提取到的所有连接表示的页面进行指定规则(回调函数)的解析
            Rule(link, callback='parse_item', follow=True),
            Rule(link1, callback='parse_item', follow=True),
        )
    
        def parse_item(self, response):
            print(response)
            
  • 相关阅读:
    pat甲级 1155 Heap Paths (30 分)
    pat甲级 1152 Google Recruitment (20 分)
    蓝桥杯 基础练习 特殊回文数
    蓝桥杯 基础练习 十进制转十六进制
    蓝桥杯 基础练习 十六进制转十进制
    蓝桥杯 基础练习 十六进制转八进制
    51nod 1347 旋转字符串
    蓝桥杯 入门训练 圆的面积
    蓝桥杯 入门训练 Fibonacci数列
    链表相关
  • 原文地址:https://www.cnblogs.com/zwq-/p/10596887.html
Copyright © 2011-2022 走看看