zoukankan      html  css  js  c++  java
  • 网络爬虫(CrawlSpider)

    阅读目录


    一、CrawlSpider简介

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

    二、CrawlSpider使用

      1.创建scrapy工程:scrapy startproject projectName

      2.创建爬虫文件:scrapy genspider -t crawl spiderName www.xxx.com

        --此指令对比以前的指令多了 "-t crawl",表示创建的爬虫文件是基于CrawlSpider这个类的,而不再是Spider这个基类。

      3.编写爬虫文件

      4.执行爬虫文件工程:scrapy crawl spiderName

    三、CrawlSpider的相关参数

      3.1 crawlspider的独特属性:

    • rules: 是Rule对象的集合,用于匹配目标网站并排除干扰
    • parse_start_url: 用于爬取起始响应,必须要返回ItemRequest中的一个。
      3.2 LinkExtractor(连接提取器) 参数:
    其中的link_extractor既可以自己定义,也可以使用已有LinkExtractor类,主要参数为:
    
    *   allow:满足括号中“正则表达式”的值会被提取,如果为空,则全部匹配。
    *   deny:与这个正则表达式(或正则表达式列表)不匹配的URL一定不提取。
    *   allow_domains:会被提取的链接的domains。
    *   deny_domains:一定不会被提取链接的domains。
    *   **restrict_xpaths**:使用**xpath**表达式,和**allow**共同作用过滤链接。还有一个类似的restrict_css

     

    # 存放定制的获取链接的规则对象(可以是一个列表也可以是元组)
    # 根据规则提取到的所有链接,会由crawlspider构建request对象,并交给引擎处理
    
    LinkExtractor : 设置提取链接的规则(正则表达式)
    allow=(), : 设置允许提取的url
    restrict_xpaths=(), :根据xpath语法,定位到某一标签下提取链接
    restrict_css=(), :根据css选择器,定位到某一标签下提取链接
    deny=(), : 设置不允许提取的url(优先级比allow高)
    allow_domains=(), : 设置允许提取url的域
    deny_domains=(), :设置不允许提取url的域(优先级比allow_domains高)
    unique=True, :如果出现多个相同的url只会保留一个
    strip=True :默认为True,表示自动去除url首尾的空格

      3.3 rules(规则解析器)参数:

    • link_extractor, : linkExtractor对象
    • callback=None, : 设置回调函数
    • follow=None, : 设置是否跟进
    • process_links=None, :可以设置回调函数,对所有提取到的url进行拦截
    • process_request=identity : 可以设置回调函数,对request对象进行拦截

      - 参数介绍:

      Rule(LinkExtractor(allow=r'Items/'), callback='parse_item', follow=True)

        参数1:指定链接提取器

        参数2:指定规则解析器解析数据的规则(回调函数)

        参数3:是否将链接提取器继续作用到链接提取器提取出的链接网页中。当callback为None,参数3的默认值为true

    四、CrawlSpider整体爬取流程:

      a)爬虫文件首先根据起始url,获取该url的网页内容

      b)链接提取器会根据指定提取规则将步骤a中网页内容中的链接进行提取

      c)规则解析器会根据指定解析规则将链接提取器中提取到的链接中的网页内容根据指定的规则进行解析

      d)将解析数据封装到item中,然后提交给管道进行持久化存储

    五、项目实战(CrawlSpider爬取东莞阳光网)

      需求:爬取全站数据,url:http://wz.sun0769.com/index.php/question/questionType?type=4&page=

       爬虫文件:dgsun.py

      CrawlSpider只需要一个起始url,即可通过连接提取器获取相应规则的url,allow中放置url提取规则(re)

      规则解析器:follow=true表示:连接提取器获取的url 继续 作用到 连接提取器提取到的连接 所对应的页面源码中,实现满足规则所有url进行全站爬取

    # -*- coding: utf-8 -*-
    import scrapy
    from scrapy.linkextractors import LinkExtractor
    from scrapy.spiders import CrawlSpider, Rule
    from ..items import DgsunproItem, ContentItem
    
    
    class DgsunSpider(CrawlSpider):
        name = 'dgsun'
        # allowed_domains = ['www.xx.com']
        # crawlSpider是通过匹配起始url+rule进行url连接提取
        start_urls = ['http://wz.sun0769.com/index.php/question/questionType?type=4&page=']
    
        # 连接提取器
        # allow=r"正则表达式" 匹配满足条件的所有url
        link1 = LinkExtractor(allow=r'type=4&page=d+')  # 提取标题页url
        link2 = LinkExtractor(allow=r'/d+/d+.shtml')  # 提取详情页url
    
        rules = (
            # 规则解析器
            # follow=True 将连接提取器 继续 作用到 连接提取器提取到的连接 所对应的页面源码中,实现全站爬取
            # follow=False 只能提取到当前HTML页面里面存在的所有url
            Rule(link1, callback='parse_item', follow=True),
            Rule(link2, callback='parse_detail', follow=False),
        )
    
        # 数据解析
        def parse_item(self, response):
            tr_list = response.xpath('//*[@id="morelist"]/div/table[2]//tr/td/table//tr')
            for tr in tr_list:
                # 标题页的文章标题
                title = tr.xpath('./td[2]/a[2]/text()').extract_first()
                # 标题页的文章ID
                num = tr.xpath('./td[1]/text()').extract_first()
    
                # 实例化item对象
                item = DgsunproItem()
                item["title"] = title
                item["num"] = num
    
                yield item
    
        # 详情页数据解析
        def parse_detail(self, response):
            # 文章详情页中的内容
            content = response.xpath('/html/body/div[9]/table[2]//tr[1]/td//text()').extract()
            content = "".join(content)
            # 文章详情页中ID
            num = response.xpath('/html/body/div[9]/table[1]//tr/td[2]/span[2]/text()').extract_first()
            num = num.split(":")[-1]
    
            # 实例化item对象
            item = ContentItem()
            item["content"] = content
            item["num"] = num
    
            yield item

      Item对象文件:存放实例化的item数据对象,items.py

      这里CrawSpider的连接提取器有两个提取规则,对应不同HTML页面,获取的内容数据的解析函数不能像spider一样请求传参,只能在items.py自定义两个Item类来存取数据,且Item中要有相同表示字段,

      否则异步请求的数据对象在管道中不能加以区分,这里我们定义两个num字段用于数据区分。

    # -*- 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 DgsunproItem(scrapy.Item):
        # define the fields for your item here like:
        title = scrapy.Field()
        # 标题页ID
        num = scrapy.Field()
    
    
    # 自定义item对象类,储存详情页内容信息
    class ContentItem(scrapy.Item):
        # define the fields for your item here like:
        content = scrapy.Field()
        # 详情页ID,需要通过两个ID建立item对象的联系,否则无法对应文章和内容信息
        num = scrapy.Field()

      配置管道文件:做数据持久化,pipelines.py

      这里通过字段对对应关系来获取数据的对应关系

    class DgsunproPipeline(object):
        # 数据持久化
        def process_item(self, item, spider):
            # 这里做持久化存储方案:
            # 数据库表中创建三个字段(num,title,content),先存放某两个字段,后存放的字段需要通过查表(where)等方式找到对应字段做存储
            if item.__class__.__name__ == "DgsunproItem":
                title = item["title"]
                num = item["num"]
            else:
                content = item["content"]
                num = item["num"]
    
            return item

      最后一步:配置settings文件,settings.py

    BOT_NAME = 'dgsunPro'
    
    SPIDER_MODULES = ['dgsunPro.spiders']
    NEWSPIDER_MODULE = 'dgsunPro.spiders'
    
    
    # Crawl responsibly by identifying yourself (and your website) on the user-agent
    USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36'
    
    # Obey robots.txt rules
    ROBOTSTXT_OBEY = False
    
    LOG_LEVEL = "ERROR"
    
    # 打开管道配置
    ITEM_PIPELINES = {
       'dgsunPro.pipelines.DgsunproPipeline': 300,
    }
  • 相关阅读:
    Git使用经验小结
    Git使用经验小结
    关于IT增值服务"拜师学艺"价格调整的通知
    关于IT增值服务"拜师学艺"价格调整的通知
    Java实现 LeetCode 397 整数替换
    Java实现 LeetCode 397 整数替换
    Java实现 LeetCode 397 整数替换
    Java实现 LeetCode 396 旋转函数
    Java实现 LeetCode 396 旋转函数
    Java实现 LeetCode 396 旋转函数
  • 原文地址:https://www.cnblogs.com/lincappu/p/12988064.html
Copyright © 2011-2022 走看看