1. 程式人生 > >scrapy框架中crawlspider的使用

scrapy框架中crawlspider的使用

一、初識crawlspider

  • 1、建立專案

    scrapy startproject 專案名稱
    
  • 2、檢視爬蟲模板

    scrapy genspider -l
    
  • 3、建立crawl模板

    scrapy genspider -t crawl 爬蟲名稱 地址
    
  • 4、自動生成模板如下

    import scrapy
    from scrapy.linkextractors import LinkExtractor
    from scrapy.spiders import CrawlSpider, Rule
    
    
    class WeisuenSpider(CrawlSpider):
        name = 'weisuen'
    allowed_domains = ['sohu.com'] start_urls = ['http://sohu.com/'] rules = ( Rule(LinkExtractor(allow=r'Items/'), callback='parse_item', follow=True), ) def parse_item(self, response): i = {} #i['domain_id'] = response.xpath('//input[@id="sid"]/@value').extract()
    #i['name'] = response.xpath('//div[@id="name"]').extract() #i['description'] = response.xpath('//div[@id="description"]').extract() return i

二、關於引數的介紹

  • 1、crawl爬蟲是繼承了CrawlSpider不是預設模板中繼承的scrapy

  • 2、新增了一個規則

    # 表示我們想提取連結中有`.shtml`字串的連結
    rules = (
            Rule(LinkExtractor(allow=
    '.shtml'), callback='parse_item', follow=True), )
  • 3、關於LinkExtractor引數的介紹

    引數名 引數含義
    allow 提取符合對應正則表示式的連結
    deny 不提取符合對應正則表示式的連結
    restrict_xpaths 使用xpath表示式與allow共用作用提取出同時符合對應xpath表示式和對應正則表示式的連結
    allow_domains 允許提取的域名,比如我只想提取某個域名下的連結時候會使用
    deny_domains 禁止提取的域名,比如我需要限制一定不提取某個域名下的連結時會使用
  • 4、舉例使用

    # 表示抓取網頁上以`shtml`結尾的url地址
    rules = (
            Rule(LinkExtractor(allow='.*?/n.*?shtml', allow_domains=('sohu.com',)), callback='parse_item', follow=True),
        )