pagination - 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)
解决方案
我发现了问题。脚本卡住了,category = category.replace("/", "")
因为某篇文章没有类别,因此终止了蜘蛛。
如果类别为空,则添加 if else 语句以继续解决它。
感谢任何读过这篇文章的人。
推荐阅读
- php - 我可以安全地更改 Symfony 4 中的 APP_SECRET 变量吗?
- mongodb - 使用更新更改集合中的值类型
- matlab - 使用 Plink 执行包含单引号的命令时出现问题
- spring - ControllerAdvice 不处理 AfterThrowing 方面抛出的异常
- julia - 如何通过从命令行执行文件来显示绘图
- yii2 - 使用 Yii2 TimestampBehavior 返回 'created_at' 没有默认值错误
- r - 在R中将字符串转换为日期格式
- python-3.x - 在 RTL 语言风格中,Psychopy 字符空间不相等
- r - 如何仅对具有相同值的序列进行分组
- java - 如何在 HTTP POST/GET 中发送空参数