W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
通過使用 ?-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
.
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: