scrapy 2.3 蜘蛛参数

2021-06-09 10:03 更新

通过使用 ​-a​ 运行它们时的选项:

scrapy crawl quotes -O quotes-humor.json -a tag=humor

这些论点被传给蜘蛛 ​__init__​ 方法并默认成为spider属性。

在本例中,为 ​tag​ 参数将通过 ​self.tag​ . 您可以使用它使您的蜘蛛只获取带有特定标记的引号,并基于以下参数构建URL::

import scrapy


class QuotesSpider(scrapy.Spider):
    name = "quotes"

    def start_requests(self):
        url = 'http://quotes.toscrape.com/'
        tag = getattr(self, 'tag', None)
        if tag is not None:
            url = url + 'tag/' + tag
        yield scrapy.Request(url, self.parse)

    def parse(self, response):
        for quote in response.css('div.quote'):
            yield {
                'text': quote.css('span.text::text').get(),
                'author': quote.css('small.author::text').get(),
            }

        next_page = response.css('li.next a::attr(href)').get()
        if next_page is not None:
            yield response.follow(next_page, self.parse)

如果你通过 ​tag=humor​ 对于这个蜘蛛,您会注意到它只访问来自 ​humor​ 标记,如 http://quotes.toscrape.com/tag/humor .


以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号