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
②能返回单个选择器
问题:
使用response.follow()方法时出现AttributeError: 'HtmlResponse' object has no attribute 'follow',如何解决?
请检查您当前使用的scrapy版本。我查看了官方的几个介绍文档,对比后发现response.follow()是在 scrapy1.4以后才有的,所以,如果你的scrapy版本低于1.4的话则不能使用此方法。你可以查看对应版本的官方文档以了解怎么使用。
比如我用的是1.3.3版本,则应该类似这样写(使用scrapy.Request()方法)
for next_page in response.css('li.nexta::attr(href)').extract():
if next_page is not None:
next_page = response.urljoin(next_page)
yield scrapy.Request(next_page, self.parse)
参考资料
https://blog.csdn.net/baidu_25555389/article/details/72590298
https://blog.csdn.net/pythonisnotshell/article/details/80538685