1. 程式人生 > >scrapy框架之CrawlSpider

scrapy框架之CrawlSpider

提問:如果想要通過爬蟲程式去爬取”糗百“全站資料新聞資料的話,有幾種實現方法?

方法一:基於Scrapy框架中的Spider的遞迴爬取進行實現(Request模組遞歸回調parse方法)。

方法二:基於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.觀察生成的爬蟲檔案

import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule


class ChoutidemoSpider(CrawlSpider):
    name 
= 'choutiDemo' #allowed_domains = ['www.chouti.com'] start_urls = ['http://www.chouti.com/'] rules = ( # 表示為提取Link規則 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

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中,然後提交給管道進行持久化儲存

ex:根據第一頁,獲取所有頁面

from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule


class CsSpider(CrawlSpider):
    name = 'cs'
    # allowed_domains = ['www.xxoo.com']
    start_urls = ['https://www.qiushibaike.com/pic/']

    link = LinkExtractor(allow=r'/pic/page/\d+/\?s=\d+')
    link1 = LinkExtractor(allow=r'/pic/page/1')  # 可以根據主頁獲取到的其他頁面,匹配獲取第一頁的url
    rules = (
        Rule(link, callback='parse_item', follow=True),  # follow=True表示根據主頁面繼續跟進,獲取其他頁的url
        Rule(link1, callback='parse_item', follow=True),
    )

    def parse_item(self, response):
        print(response)  # 可以看到大於的response中顯示了所有頁碼的url