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

How to use response.css() with response.follow() for pagination for the last page in Scrapy?

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

    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: list index out of range",我可以用 try, except, else 来处理:

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

我在问是否有更好更短的方法来解决这个问题,还是我应该坚持使用旧的 response.url() 方法进行分页?我问这个是因为我在他们的发行说明中以粗体显示 "it is now a recommended way to create Requests in Scrapy spiders".

使用release note方式如何?

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执行
  • 最后一个分隔符用于处理页面包含多个下一个元素。