import scrapy
class QuotesSpider(scrapy.Spider):
name = "quotes"
start_urls = [
'http://quotes.toscrape.com/page/1/',
]
def parse(self, response):
for quote in response.css('div.quote'):
yield {
'text': quote.css('span.text::text').extract_first(),
'author': quote.css('span small::text').extract_first(),
'tags': quote.css('div.tags a.tag::text').extract(),
}
next_page = response.css('li.next a::attr(href)').extract_first()
if next_page is not None:
yield response.follow(next_page, callback=self.parse)
与scrapy.Request不同,response.follow
直接支持相对URL - 无需调用urljoin。 请注意,response.follow
只是返回一个Request实例;你仍然需要产生这个请求。
您也可以将选择器传递给response.follow
代替字符串;该选择器应该提取必要的属性:
for a in response.css('li.next a'):
yield response.follow(a, callback=self.parse)
注意
response.follow(response.css('li.next a'))
无效,因为response.css
返回一个包含所有结果选择器的类似列表的对象,而不是单个选择器。 如上例所示的for
循环,或response.follow(response.css('li.nexta')[0])
是可以的。
总结: response.follow()
①支持相对url
②能返回单个选择器