首页 > 解决方案 > 使用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>
...

下一页链接: https ://schwangerschaft.gofeminin.de/forum/all/p2

标签: pythonxpathscrapycss-selectorsweb-crawler

解决方案


试试response.css('link[rel=next]::attr(href)').get(),这应该可以。


推荐阅读