scrapy 2.3 蜘蛛?yún)?shù)

2021-06-09 10:03 更新

通過使用 ?-a? 運行它們時的選項:

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

這些論點被傳給蜘蛛 ?__init__? 方法并默認成為spider屬性。

在本例中,為 ?tag? 參數(shù)將通過 ?self.tag? . 您可以使用它使您的蜘蛛只獲取帶有特定標記的引號,并基于以下參數(shù)構(gòu)建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 .


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號