python - 使用 BeautifulSoup 解析谷歌新闻
问题描述
我正在尝试从新闻搜索“测试”Google 中解析每个新闻元素的标题和文本。
Each element contains the g-card tag:
当我尝试使用解析时:
from bs4 import BeautifulSoup
import requests
url="https://www.google.com/search?q=bitcoin&sxsrf=ALeKk00r2AqKlBSgzF1T_zG1uQBaBKSN1g:1612525788197&source=lnms&tbm=nws&sa=X&ved=2ahUKEwji6q7W1tLuAhW0ShUIHSGmBpoQ_AUoAXoECBcQAw&biw=2513&bih=1315"
code=requests.get(url)
soup=BeautifulSoup(code.text,"html.parser")
soup.find_all("g-card")
结果是一个空列表:
[]
我应该如何修改find_all
以返回允许从每个结果中选择标题和文本的新闻结果?
解决方案
您尝试解析的网站是动态的(意味着 js 需要在浏览器中运行,以便呈现给您显示的 HTML)
因此,使用requests
获取 HTML 只会导致在运行 js 之前返回整个页面源。
因此,要解析动态网站,您必须使用类似selenium
在浏览器中运行 js 之类的东西,然后您可以从中获取 HTML 文件并使用BeautifulSoup
.
推荐阅读
- sql - 更改sql上的日期
- sql-server - 每次舍入大于等于 0.01 时重置求和十进制值
- java - 如何获取运行 Java 应用程序的 GAE 项目的 ID?
- google-apps-script - 用户关闭浏览器窗口时的提示
- php - 如何链接 laravel 模型查询构建器
- tensorflow - Keras 保存的模型在多个 GPU 上使用 Batch Normalization 返回与原始模型不同的结果(分布式训练)
- google-apps-script - Webapp - 你能分离出客户端js吗?
- python - Pygame 移动的星星
- laravel - 前端 laravel fortify 上未显示错误消息
- powerquery - PowerQuery 根据键列选择值