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
相关文章
相关标签/搜索