You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Scrapy用CSS选择器翻页时重复抓取首页数据的修正方案

问题修正方案

核心原因

你的代码中分页链接的选择器未精准定位到「下一页」按钮,导致每次抓取的都是当前页(第一页)的链接,进而重复请求同一页面。

修正步骤

  1. 确认下一页按钮结构:打开目标网站分页区域,通过浏览器开发者工具查看「下一页」按钮的HTML标识,通常这类按钮会带有next类名(如li.page-item.next)。
  2. 替换精准选择器:将原选择器修改为定位下一页按钮的版本:
next_page = response.css("ul.pagination li.page-item.next a.page-link::attr(href)").get()
if next_page is not None:
    next_page = response.urljoin(next_page)
    yield scrapy.Request(next_page, callback=self.parse)
  1. 验证选择器有效性:在Scrapy Shell中测试选择器是否返回正确的下一页URL:
scrapy shell https://www.propertypro.ng/property-for-sale
response.css("ul.pagination li.page-item.next a.page-link::attr(href)").get()

若返回/property-for-sale?page=2这类带页码的链接,说明选择器有效。

备选XPath方案

如果CSS选择器不生效,改用XPath定位下一页链接:

next_page = response.xpath("//ul[contains(@class, 'pagination')]//li[contains(@class, 'next')]/a/@href").get()
if next_page is not None:
    next_page = response.urljoin(next_page)
    yield scrapy.Request(next_page, callback=self.parse)

内容的提问来源于stack exchange,提问作者Akpakli Edudzi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 06:01:02