• 爬虫框架Scrapy之CrawlSpiders


    CrawlSpiders

    通过下面的命令可以快速创建 CrawlSpider模板 的代码:

    scrapy genspider -t crawl tencent tencent.com

    上一个案例中,我们通过正则表达式,制作了新的url作为Request请求参数,现在我们可以换个花样...

    class scrapy.spiders.CrawlSpider

    它是Spider的派生类,Spider类的设计原则是只爬取start_url列表中的网页,而CrawlSpider类定义了一些规则(rule)来提供跟进link的方便的机制,从爬取的网页中获取link并继续爬取的工作更适合。

    CrawlSpider继承于Spider类,除了继承过来的属性外(name、allow_domains),还提供了一个新的属性和方法:

    rules

    在rules中包含一个或多个Rule对象,每个Rule对爬取网站的动作定义了特定操作。如果多个rule匹配了相同的链接,则根据规则在本集合中被定义的顺序,第一个会被使用。

    
    class scrapy.contrib.spiders.Rule(
            link_extractor, 
            callback = None, 
            cb_kwargs = None, 
            follow = None, 
            process_links = None, 
            process_request = None
    )
    
    • link_extractor:是一个Link Extractor对象,用于定义需要提取的链接。

    • callback: 从link_extractor中每获取到链接时,参数所指定的值作为回调函数,该回调函数接受一个response作为其第一个参数。

      注意:当编写爬虫规则时,避免使用parse作为回调函数。由于CrawlSpider使用parse方法来实现其逻辑,如果覆盖了 parse方法,crawl spider将会运行失败。

    • follow:是一个布尔(boolean)值,指定了根据该规则从response提取的链接是否需要跟进。 如果callback为None,follow 默认设置为True ,否则默认为False。

    • process_links:指定该spider中哪个的函数将会被调用,从link_extractor中获取到链接列表时将会调用该函数。该方法主要用来过滤。

    • process_request:指定该spider中哪个的函数将会被调用, 该规则提取到每个request时都会调用该函数。 (用来过滤request)

    parse_start_url(response):

    当start_url的请求返回时,该方法被调用。

    LinkExtractors

    class scrapy.linkextractors.LinkExtractor
    

    Link Extractors 的目的很简单: 提取链接。

    每个LinkExtractor有唯一的公共方法是 extract_links(),它接收一个 Response 对象,并返回一个 scrapy.link.Link 对象。

    Link Extractors要实例化一次,并且 extract_links 方法会根据不同的 response 调用多次提取链接。

    classscrapy.contrib.linkextractors.sgml.SgmlLinkExtractor(
        allow = (),
        deny = (),
        allow_domains = (),
        deny_domains = (),
        deny_extensions = None,
        restrict_xpaths = (),
        tags = ('a','area'),
        attrs = ('href'),
        canonicalize = True,
        unique = True,
        process_value = None
    )
    

    主要参数:

    • allow:满足括号中“正则表达式”的值会被提取,如果为空,则全部匹配。

    • deny:与这个正则表达式(或正则表达式列表)不匹配的URL一定不提取。

    • allow_domains:会被提取的链接的domains。

    • deny_domains:一定不会被提取链接的domains。

    • restrict_xpaths:使用xpath表达式,和allow共同作用过滤链接。

    爬取规则(Crawling rules)

    继续用腾讯招聘为例,给出配合rule使用CrawlSpider的例子:

    1. 首先运行

       scrapy shell "http://hr.tencent.com/position.php?&start=0#a"
      
    2. 导入LinkExtractor,创建LinkExtractor实例对象。:

       from scrapy.linkextractors import LinkExtractor
      
       page_lx = LinkExtractor(allow=('position.php?&start=d+'))
      

      allow : LinkExtractor对象最重要的参数之一,这是一个正则表达式,必须要匹配这个正则表达式(或正则表达式列表)的URL才会被提取,如果没有给出(或为空), 它会匹配所有的链接。

      deny : 用法同allow,只不过与这个正则表达式匹配的URL不会被提取)。它的优先级高于 allow 的参数,如果没有给出(或None), 将不排除任何链接。

    3. 调用LinkExtractor实例的extract_links()方法查询匹配结果:

       page_lx.extract_links(response)
      
    4. 没有查到:

       []
      
    5. 注意转义字符的问题,继续重新匹配:

       page_lx = LinkExtractor(allow=('position.php?&start=d+'))
       # page_lx = LinkExtractor(allow = ('start=d+'))
      
       page_lx.extract_links(response)
      

    CrawlSpider版本

    那么,scrapy shell测试完成之后,修改以下代码

    #提取匹配 'http://hr.tencent.com/position.php?&start=d+'的链接
    page_lx = LinkExtractor(allow = ('start=d+'))
    
    rules = [
        #提取匹配,并使用spider的parse方法进行分析;并跟进链接(没有callback意味着follow默认为True)
        Rule(page_lx, callback = 'parse', follow = True)
    ]
    

    这么写对吗?

    不对!千万记住 callback 千万不能写 parse,再次强调:由于CrawlSpider使用parse方法来实现其逻辑,如果覆盖了 parse方法,crawl spider将会运行失败。

    #tencent.py
    
    import scrapy
    from scrapy.spiders import CrawlSpider, Rule
    from scrapy.linkextractors import LinkExtractor
    from mySpider.items import TencentItem
    
    class TencentSpider(CrawlSpider):
        name = "tencent"
        allowed_domains = ["hr.tencent.com"]
        start_urls = [
            "http://hr.tencent.com/position.php?&start=0#a"
        ]
    
        page_lx = LinkExtractor(allow=("start=d+"))
    
        rules = [
            Rule(page_lx, callback = "parseContent", follow = True)
        ]
    
        def parseContent(self, response):
            for each in response.xpath('//*[@class="even"]'):
                name = each.xpath('./td[1]/a/text()').extract()[0]
                detailLink = each.xpath('./td[1]/a/@href').extract()[0]
                positionInfo = each.xpath('./td[2]/text()').extract()[0]
    
                peopleNumber = each.xpath('./td[3]/text()').extract()[0]
                workLocation = each.xpath('./td[4]/text()').extract()[0]
                publishTime = each.xpath('./td[5]/text()').extract()[0]
                #print name, detailLink, catalog,recruitNumber,workLocation,publishTime
    
                item = TencentItem()
                item['name']=name.encode('utf-8')
                item['detailLink']=detailLink.encode('utf-8')
                item['positionInfo']=positionInfo.encode('utf-8')
                item['peopleNumber']=peopleNumber.encode('utf-8')
                item['workLocation']=workLocation.encode('utf-8')
                item['publishTime']=publishTime.encode('utf-8')
    
                yield item
    
        # parse方法当然也可以不写     
        def parse(self, response):                                              
             pass
    

    运行: scrapy crawl tencent

    Logging

    Scrapy提供了log功能,可以通过 logging 模块使用。

    可以修改配置文件settings.py,任意位置添加下面两行,效果会清爽很多。

    LOG_FILE = "TencentSpider.log"
    LOG_LEVEL = "INFO"
    

    Log levels

    • Scrapy提供5层logging级别:

    • CRITICAL - 严重错误(critical)

    • ERROR - 一般错误(regular errors)
    • WARNING - 警告信息(warning messages)
    • INFO - 一般信息(informational messages)
    • DEBUG - 调试信息(debugging messages)

    logging设置

    通过在setting.py中进行以下设置可以被用来配置logging:

    1. LOG_ENABLED 默认: True,启用logging
    2. LOG_ENCODING 默认: 'utf-8',logging使用的编码
    3. LOG_FILE 默认: None,在当前目录里创建logging输出文件的文件名
    4. LOG_LEVEL 默认: 'DEBUG',log的最低级别
    5. LOG_STDOUT 默认: False 如果为 True,进程所有的标准输出(及错误)将会被重定向到log中。例如,执行 print "hello" ,其将会在Scrapy log中显示。
  • 相关阅读:
    如何停止CLOSE_WAIT端口:How do I remove a CLOSE_WAIT socket connection
    HttpServer:JDK 内置的轻量级 HTTP 服务器
    Create a git patch from the uncommitted changes in the current working directory
    mac Zip 常用命令
    Mac下php服务部署
    [转]Linux Programming Made Easy – A Complete Guide With Resources For Beginners
    【转】kubevirt在360的探索之路(k8s接管虚拟化)
    【转】KubeSphere 多集群管理大招:使用 QKE 管理多个 ACK 集群
    [转]深入理解CNI(容器网络接口)
    【转】再谈自研开源KubeOVN, 设计思路及实现原理
  • 原文地址:https://www.cnblogs.com/wzjbg/p/6507572.html
Copyright © 2020-2023  润新知