Scrapy用CSS选择器翻页时重复抓取首页数据的修正方案
问题修正方案
核心原因
你的代码中分页链接的选择器未精准定位到「下一页」按钮,导致每次抓取的都是当前页(第一页)的链接,进而重复请求同一页面。
修正步骤
- 确认下一页按钮结构:打开目标网站分页区域,通过浏览器开发者工具查看「下一页」按钮的HTML标识,通常这类按钮会带有
next类名(如li.page-item.next)。 - 替换精准选择器:将原选择器修改为定位下一页按钮的版本:
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)
- 验证选择器有效性:在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
相关产品推荐
相关产品推荐

