python - 使用scrapy找到正确的分页选择器
问题描述
我正在尝试从该论坛中提取数据:
https://schwangerschaft.gofeminin.de/forum/all
我从第一页获取数据。我使用 css 选择器'li.selected > a::attr(href)'
不幸的是,我无法从其他页面获取所有其他数据。
用于分页的 xpath 或 css 选择器的正确路径是什么?
Python:
import scrapy
class ForumSpider(scrapy.Spider):
name = "pregnancy"
def start_requests(self):
url = 'https://schwangerschaft.gofeminin.de/forum/all'
yield scrapy.Request(url, self.parse)
def parse(self, response):
for thread in response.css('div.af-thread-item'):
yield{
'threadTitle': thread.css('span.thread-title::text').extract_first(),
'username': thread.css('div.user-name::text').extract_first()
}
next_page = response.css('li.selected > a::attr(href)').extract_first()
if next_page is not None:
yield scrapy.Request(response.urljoin(next_page))
HTML:
<nav class="af-pagination " role="navigation"><ul><li class="selected">
<a href="https://schwangerschaft.gofeminin.de/forum/all">1</a></li><li>
<a href="https://schwangerschaft.gofeminin.de/forum/all/p2">2</a></li><li>
<a href="https://schwangerschaft.gofeminin.de/forum/all/p3">3</a></li><li>
<a href="https://schwangerschaft.gofeminin.de/forum/all/p4">4</a></li><li>
<a href="https://schwangerschaft.gofeminin.de/forum/all/p5">5</a></li><li>
<a href="https://schwangerschaft.gofeminin.de/forum/all/p6">6</a></li><li>
<a href="https://schwangerschaft.gofeminin.de/forum/all/p7">7</a></li><li>
<a href="https://schwangerschaft.gofeminin.de/forum/all/p8">8</a></li><li>
...
解决方案
试试response.css('link[rel=next]::attr(href)').get()
,这应该可以。
推荐阅读
- java - 解析发射器 LibGDX ParticleEffects 时出错
- javascript - 如何让我的云代码在我的工人测功机而不是网络测功机上运行?
- three.js - Three.js:动态缩放/旋转 alpha 掩码——2018 年最佳实践?
- android - 所选图像的路径为空
- amazon-web-services - 在具有共享代码的多个服务的 monorepo 上使用无服务器框架
- node.js - 无法在节点中发出包含数组的发布请求
- c# - C# Linq Entity Framework - 通过修改 Excel 单元格值来更新数据库
- html - 滚动覆盖另一个 div 的 div
- python - boto3.client('S3') 返回什么?
- java - 如何在使用 openCSV 写入 .csv 文件时添加分隔符