首页 > 解决方案 > 如何使用 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,依此类推,没有可辨别的模式。我一直无法找到一个教程来教我如何处理这种情况

标签: pythonweb-scrapingscrapyxmlhttprequest

解决方案


如果您使用表单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属性的值是您要发出下一个请求的值。


推荐阅读