Scrapy 1.5.0之爬取規則

Spiders參數

spiders能夠經過接收參數來修改其爬取行爲。crawl 經過使用選項 -a 傳遞爬蟲參數。php

scrapy crawl myspider -a category=electronics

spiders 在構造函數中接收參數:html

import scrapy

class MySpider(scrapy.Spider):
    name = 'myspider'

    def __init__(self, category=None, *args, **kwargs):
        super(MySpider, self).__init__(*args, **kwargs)
        self.start_urls = ['http://www.example.com/categories/%s' % category]
        # ...

也能夠經過Scrapyd schedule.json API傳遞spiders參數。python

Generic Spiders(通用爬蟲)

舉個例子,在項目中假設在myproject.items中定義了一個TestItem類,以下圖。json

import scrapy

class TestItem(scrapy.Item):
    id = scrapy.Field()
    name = scrapy.Field()
    description = scrapy.Field()

CrawlSpider

class scrapy.spiders.CrawlSpiderdom

爬取通常網站經常使用的spider。其定義了一些規則(rule)來提供跟進link的方便的機制。electron

除了從Spider繼承過來的(您必須提供的)屬性外,其提供了一個新的屬性:scrapy

  • rules

一個包含一個(或多個) Rule 對象的集合(list)。 每一個 Rule 對爬取網站的動做定義了特定表現。若是多個rule匹配了相同的連接,則根據他們在本屬性中被定義的順序,第一個會被使用。ide

該spider也提供了一個可複寫(overrideable)的方法:函數

  • parse_start_url(response)

start_url的請求返回時,該方法被調用。 該方法分析最初的返回值並必須返回一個 Item 對象或者一個 Request 對象或者一個可迭代的包含兩者對象。網站

class scrapy.spiders.Rule(爬取規則)

參數

  • link_extractor 是一個 Link Extractor 對象。 其定義瞭如何從爬取到的頁面提取連接。
  • callback 是一個callable或string(該spider中同名的函數將會被調用)。 從link_extractor中每獲取到連接時將會調用該函數。該回調函數接受一個response做爲其第一個參數, 並返回一個包含 Item 以及(或) Request 對象(或者這二者的子類)的列表(list)。

警告

當編寫爬蟲規則時,請避免使用 parse 做爲回調函數。 因爲 CrawlSpider 使用 parse 方法來實現其邏輯,若是 您覆蓋了 parse 方法,crawl spider 將會運行失敗。

  • cb_kwargs 包含傳遞給回調函數的參數(keyword argument)的字典。
  • follow 是一個布爾(boolean)值,指定了根據該規則從response提取的連接是否須要跟進。 若是 callback 爲None, follow 默認設置爲 True ,不然默認爲 False 。
  • process_links 是一個callable或string(該spider中同名的函數將會被調用)。 從link_extractor中獲取到連接列表時將會調用該函數。該方法主要用來過濾。
  • process_request 是一個callable或string(該spider中同名的函數將會被調用)。 該規則提取到每一個request時都會調用該函數。該函數必須返回一個request或者None。 (用來過濾request)

CrawlSpider樣例

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

class MySpider(CrawlSpider):
    name = 'example.com'
    allowed_domains = ['example.com']
    start_urls = ['http://www.example.com']

    rules = (
        # 提取匹配 'category.php' (但不匹配 'subsection.php') 的連接並跟進連接(沒有callback意味着follow默認爲True)
        Rule(LinkExtractor(allow=('category\.php', ), deny=('subsection\.php', ))),

        # 提取匹配 'item.php' 的連接並使用spider的parse_item方法進行分析
        Rule(LinkExtractor(allow=('item\.php', )), callback='parse_item'),
    )

    def parse_item(self, response):
        self.logger.info('Hi, this is an item page! %s', response.url)

        item = scrapy.Item()
        item['id'] = response.xpath('//td[@id="item_id"]/text()').re(r'ID: (\d+)')
        item['name'] = response.xpath('//td[@id="item_name"]/text()').extract()
        item['description'] = response.xpath('//td[@id="item_description"]/text()').extract()
        return item
相關文章
相關標籤/搜索