python - 如何使用 Scrapy 通过“显示更多”按钮递归滚动浏览新闻页面
问题描述
我对网络抓取非常陌生,并且我对社会科学项目有一个特定的问题。我正在尝试爬取 bbc 新闻博客 ( https://www.bbc.com/news/blogs/the_papers ),打开每篇文章并搜索一个词的出现率。到目前为止,我的蜘蛛看起来像这样:
class NewsSpider(scrapy.Spider):
name = 'news_spider'
start_urls = ['https://www.bbc.com/news/blogs/the_papers']
data_array = []
def parse(self, response):
self.logger.info('news blog data:')
news_blogs = response.css('div.blog__story.story-inner')
for blog in news_blogs:
link = blog.css('a::attr(href)').get()
data_point = blog_parser(link, 'immigration')
self.logger.info(link)
self.logger.info(data_point.showData())
yield {
'text': blog.css('span.cta::text').get()
}
该刮板适用于网站的第一页。我的问题是我需要点击页面底部的“更多故事”按钮,并尽可能多次递归地抓取新数据。为此,我知道我需要模仿单击按钮时发出的请求
每次单击更多故事按钮时,都会有一个表单的 xhr 请求:https ://www.bbc.com/news/ssi/components.html?batch[blog][opts][asset_id]=blogs/the_papers&before= X
但是没有可以递归复制的模式,我的意思是第一个参数 x 是 1583453829,下一个是 1582674398,依此类推,没有可辨别的模式。我一直无法找到一个教程来教我如何处理这种情况
解决方案
如果您使用表单https://www.bbc.com/news/ssi/components.html?batch[blog][opts][asset_id]=blogs/the_papers&before=x挖掘每个 XHR 请求的响应,您可以找到响应开头的元素,如下所示:
<div class="blog__stories story-body" id="comp-blog" data-next="/news/ssi/components.html?batch[blog][opts][asset_id]=blogs/the_papers&before=1583796820" >
该data-next
属性的值是您要发出下一个请求的值。
推荐阅读
- spring-boot - OpenApi 使用 JSON 发送 MultipartFile 请求获取“应用程序/八位字节流”错误不支持
- html - 如何让这个网站响应?
- python - Python - Can't Get Pandas and Numpy Working in Visual Studio Code or Eclipse
- python - 调用没有所有给定参数的函数
- kubernetes - 由于 CNI 插件未初始化,Kubernetes 工作节点未就绪
- javascript - 为什么结果与我的预期不同?
- ocaml - 如何在 OCaml 的函数中将字符串变量作为参数传递?
- ios - 为什么自定义 SwiftUI 视图在 ViewModel 状态更改时没有动画?
- excel - 如何同时粘贴链接和转置?
- python - 如何使用预训练模型的模型架构但没有权重