Scrapy Spider 如何避免当前页面和下一页之间的无限循环

Scrapy Spider How to avoid endless cycle between current and next page

我正在尝试抓取多个页面,但我的爬虫最终在第 1 页和第 2 页之间循环。如何编写一个只向前移动的脚本?我尝试了以下选择器,但无法从第 1 页移动到第 2 页。

NEXT_PAGE_SELECTOR = '//span[@class="page-link"]//span[contains(text(),"»")]/preceding-sibling::a/@href'
nextPageUrl = response.urljoin(response.xpath(NEXT_PAGE_SELECTOR).extract_first())

第 1 页

<span class="page-link"><a href=".../page/2/"><span aria-hidden="true">»</span><span class="sr-only">Next page</span></a></span>

第 2 页

<span class="page-link"><a href=".../page/1/"><span aria-hidden="true">«</span><span class="sr-only">Previous page</span></a></span>

谢谢

很难调试使用 NEXT_PAGE_SELECTOR 时发生的事情。还有另一种更简单的方法可以遍历您需要的所有页面。您可以使用 CrawlSpider 的 "parse" 方法。在 "parse" 方法中,您可以从页面获取数据,然后获取下一页 URL 以回调等于 self.parse 的收益。它将再次打开下一页 URL 和 运行 "parse" 方法,下一页 URL 响应。

from scrapy.spiders import CrawlSpider


class SomeSpider(CrawlSpider):
    name = 'SAME NAME'
    allowed_domains = ['ALLOWED DOMAINS HERE']
    start_urls = ['START_URL'

    def parse(self, response):
        # First you get all data from current page.
        urls = response.css('div.title a::attr(href)').extract()

        for url in urls:
            yield response.follow(url, callback=self.parse_data_page)

        # Second you get next page URL and yield it with callback.
        next_page = response.css('span.page-link a::attr(href)').extract_first()
        yield response.follow(next_page, callback=self.parse})

    def parse_data_page(self, response):
        # Pars