Skip to main content
 首页 » 编程设计

python之如何使用 response.css() 和 response.follow() 在 Scrapy 中对最后一页进行分页

2025年02月15日8itcoder

这是我从第一页到最后一页的分页代码:

    url = response.css("li.next a::attr(href)").extract_first() 
    if url: 
        url = response.urljoin(url) 
        yield response.follow(url, self.parse) 

Scrapy 1.4 release notes还有另一种方法:

for a in response.css('li.page a'): 
    yield response.follow(a, self.parse) 

我试过这个:

    url = response.css("li.next a")[0] 
    if url: 
        yield response.follow(url, self.parse) 

但我在最后一页中收到错误“IndexError:列表索引超出范围”,我可以用 try,except,else 处理:

    try: 
        url = response.css("li.next a")[0] 
    except IndexError: 
        pass 
    else: 
        yield response.follow(url, self.parse) 

我在问是否有更好更短的方法来解决这个问题,还是我应该坚持使用旧的 response.url() 方法进行分页?我问这个是因为我在他们的发行说明中看到了这个,用粗体显示,“它现在是在 Scrapy 蜘蛛中创建请求的推荐方法”。

请您参考如下方法:

使用发行说明方式怎么样?

for a in response.css('li.next a'): 
    yield response.follow(a, self.parse) 
 
    # if more than one next can be found and you just need the first 
    # break 
  • 如果没有给定选择器的元素,则不会激活循环
  • 如果有下一个元素,可以yield执行。
  • 最后一个中断用于处理页面包含多个下一个元素。