首页 > 解决方案 > 点击“加载更多新闻”按钮后 Python 抓取页面

问题描述

我可以使用以下代码来抓取财经新闻网站的首页。

df = pd.DataFrame()
url = 'https://std.stheadline.com/realtime/finance/%E5%8D%B3%E6%99%82-%E8%B2%A1%E7%B6%93'
result = requests.get(url)
result.raise_for_status()
result.encoding = "utf-8"

要下载后续页面,我需要单击“加载更多新闻”按钮。我使用 Chrome>Inspect>Network 检查了该网站。我发现点击“加载更多新闻”按钮后,请求 URL 是“https://std.stheadline.com/realtime/get_more_news”和表单数据;是“cat=finance&page=3”。我将这两个放在一起并添加了“?” 介于两者之间。但是,这样的 URL 不起作用。有什么遗漏吗?

url="https://std.stheadline.com/realtime/get_more_news?cat=finance&page=3"

标签: python-3.xurlweb-scraping

解决方案


该按钮实际上是一个POST请求,因此无需查找 API 之外的任何内容,然后发出正确的请求。

就是这样:

import requests

headers = {
    "Referer": "https://std.stheadline.com/realtime/finance/",
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:83.0) Gecko/20100101 Firefox/83.0",
    "X-Requested-With": "XMLHttpRequest",
}
payload = {
    "cat": "finance",
    "page": 4,
}
print(requests.post("https://std.stheadline.com/realtime/get_more_news/", data=payload, headers=headers).json())

这将为您“加载”下一页的新闻。


推荐阅读