首页 > 解决方案 > Scrapy不遵循分页链接

问题描述

我正在尝试从https://www.finextra.com/latest-news抓取新闻文章

我已经查看了 stackoverflow 上关于scrapy 分页问题的类似问题,但似乎没有一个反映我的问题。

除了我想关注“next_page”链接的部分之外,我的代码中的所有内容都有效。我使用完全相同的代码(除了 xpath 选择器)为另一个新闻网站编写了另一个蜘蛛,它运行良好。

我检查了 xpath 选择器是否正确提取了链接,并且由于一些答案表明中间件存在问题,我已经注释掉了 allowed_domains 。

有人能帮助我吗。

class FinextraSpider(scrapy.Spider):
    name = 'finextra'
    # allowed_domains = ["finextra.com"]
    start_urls = ["https://www.finextra.com/latest-news"]

    def parse(self, response):
        articles = response.xpath("//div[@class='module--story']")

        for article in articles:
            category = article.xpath("./div[@class='story--content']/h6/a/text()").get()
            category = category.replace("/", "")
            article_link = article.xpath("./div[@class='story--content']/h4/a/@href").get()
            title = article.xpath("./div[@class='story--content']/h4/a/text()").get()
            title = title.replace("'", "''")

            yield scrapy.Request(response.urljoin(article_link),
                                  cb_kwargs={'category': category,
                                             'article_link': article_link,
                                             'title': title},
                                  callback=self.parse_readmore)

        # DOESNT WORK
        next_page = response.xpath("//div[@id='pagination']/a[last()-1]/@href")
        if next_page:
            yield response.follow(next_page,
                                  callback=self.parse)

标签: paginationscrapy

解决方案


我发现了问题。脚本卡住了,category = category.replace("/", "")因为某篇文章没有类别,因此终止了蜘蛛。

如果类别为空,则添加 if else 语句以继续解决它。

感谢任何读过这篇文章的人。


推荐阅读