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
②能返回单个选择器
本文介绍使用Scrapy框架抓取网站上的名言警句。通过定义Spider类并利用response.follow简化页面翻页逻辑,实现数据高效抓取。文章还详细解释了response.follow的使用方法及其优势。

被折叠的 条评论
为什么被折叠?



