scrapy2.0部分新功能
"""
<ul class="pager">
<li class="next">
<a href="/page/2/">Next <span aria-hidden="true">→</span></a>
</li>
</ul>
"""
回顾翻页操作
"""
start_urls = [ 'http://quotes.toscrape.com/page/1/']
...
next_page = response.css('li.next a::attr(href)').get()
if next_page is not None:
next_page = response.urljoin(next_page) # urljoin的功能 http://quotes.toscrape.com/page/2/
yield scrapy.Request(next_page, callback=self.parse)
"""
response.follow 直接支持相对URL-无需调用URLJOIN。注意 response.follow 只返回一个请求实例;您仍然需要生成这个请求。
"""
next_page = response.css('li.next a::attr(href)').get()
if next_page is not None:
yield response.follow(next_page, callback=self.parse)
"""
为了 <a> 元素有一个快捷方式: response.follow 自动使用其href属性。因此代码可以进一步缩短:
"""
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.next a')[0]) 很好。
新功能之一
#要从一个可迭代对象创建多个请求,可以response.follow_all改为使用
"""
anchors = response.css('ul.pager a')
yield from response.follow_all(anchors, callback=self.parse)
"""
#或者,将其进一步缩短,在翻页爬取的时候一行代码就搞定了
不用if判断下一页所在标签里面是否有链接,因为只有有链接才会yield
"""
yield from response.follow_all(css='ul.pager a', callback=self.parse)
"""
#这个在简单爬取时可以使用,不过如果中间还有什么逻辑,就不太适用了,下面的栗子可以看的出来,毕竟一行吧
"""
next_page = response.css('li.next a::attr(href)').get()
if next_page is not None:
print("自己编写的其他逻辑,例如记录一下当前第几页了等等")
yield response.follow(next_page, callback=self.parse)
"""
Scrapy 2.0翻页爬取简化
本文介绍Scrapy 2.0中翻页爬取的简化方法,利用response.follow和response.follow_all函数,使代码更简洁高效。通过实例展示了如何自动处理相对URL,减少代码量并提高可读性。





