我试着从这个论坛中提取数据:
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>
...
发布于 2019-01-18 08:39:54
尝试response.css('link[rel=next]::attr(href)').get()
,这应该可以工作。
发布于 2019-01-18 09:02:15
考虑到这个网站导航栏的构建方式,我喜欢在这些情况下使用xpath。假设当前页面将有一个"selected“类,我将选择"selected”类,然后使用索引为1的“following sibling”语法来获得下面的标记。
在您的案例中:
response.xpath("//li[@class='selected']/following-sibling::li[1]/a/@href").extract_first()
所以无论你在哪个页面,你都会动态地选择“下一页”。
https://stackoverflow.com/questions/54250214
复制相似问题