python - 如何在 python 中抓取某些 html 类
问题描述
我正在尝试抓取一个随机站点并从页面中获取具有特定类别的所有文本。
from bs4 import BeautifulSoup
import requests
sources = ['https://cnn.com']
for source in sources:
page = requests.get(source)
soup = BeautifulSoup(page.content, 'html.parser')
results = soup.find_all("div", class_='cd_content')
for result in results:
title = result.find('span', class_="cd__headline-text vid-left-enabled")
print(title)
从我在网上找到的内容来看,这应该可以,但由于某种原因,它找不到任何东西,结果是空的。任何帮助是极大的赞赏。
解决方案
检查网络调用后,您会看到页面是通过向以下位置发送GET
请求动态加载的:
https://www.cnn.com/data/ocs/section/index.html:homepage1-zone-1/views/zones/common/zone-manager.izl
HTMLhtml
在页面上的键中可用
import requests
from bs4 import BeautifulSoup
URL = "https://www.cnn.com/data/ocs/section/index.html:homepage1-zone-1/views/zones/common/zone-manager.izl"
response = requests.get(URL).json()["html"]
soup = BeautifulSoup(response, "html.parser")
for tag in soup.find_all(class_="cd__headline-text vid-left-enabled"):
print(tag.text)
输出(截断):
This is the first Covid-19 vaccine in the US authorized for use in younger teens and adolescents
When the US could see Covid cases and deaths plummet
'Truly, madly, deeply false': Keilar fact-checks Ron Johnson's vaccine claim
These are the states with the highest and lowest vaccination rates
推荐阅读
- javascript - SyntaxError:类属性声明上的意外标识符
- java - Project reactor - 如果其他两个并行通量请求已完成,则取消通量 REST API 请求
- python - 如何在我需要我的话后删除单词
- reactjs - 如何阻止 UseEffect 运行外部代码
- reactjs - 如何在 React 中从另一个组件调用一个组件的功能
- javascript - 由于 Eslint 错误,Vue Js 未部署到 Firebase
- java - Visual Studio Code maven 项目 - 如何添加源文件夹
- reactjs - 试图制作一个 onclick 按钮,但它一直说 showTest 未定义
- wpf - Visual Studio XAML 编辑器:剪切和粘贴一段代码时,如何使其保持折叠状态?
- javascript - 无法获取数组的值