首页 > 解决方案 > 使用 BeautifulSoup 解析谷歌新闻

问题描述

我正在尝试从新闻搜索“测试”Google 中解析每个新闻元素的标题和文本。

The search URL is : https://www.google.com/search?biw=2513&tbm=nws&sxsrf=ALeKk02tev7vVkPiKz3E20Lih1-7Ol8SBw%3A1612526096099&ei=EDIdYNXbBdmc1fAPid678A0&q=test&oq=test&gs_l=psy-ab.3..0l10.25658.26016.0.26105.4.4. 0.0.0.0.74.204.3.3.0....0...1c.1.64.psy-ab..1.3.202....0.y_53L-Gyyyw

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以返回允许从每个结果中选择标题和文本的新闻结果?

标签: pythonbeautifulsoup

解决方案


您尝试解析的网站是动态的(意味着 js 需要在浏览器中运行,以便呈现给您显示的 HTML)

因此,使用requests获取 HTML 只会导致在运行 js 之前返回整个页面源。

因此,要解析动态网站,您必须使用类似selenium在浏览器中运行 js 之类的东西,然后您可以从中获取 HTML 文件并使用BeautifulSoup.


推荐阅读