python - 使用 Beautiful Soup 解析结构复杂的 HTML
问题描述
对于noob html抓取问题感到抱歉,但我正在处理复杂的html,每种情况都是独一无二的。
我正在尝试解析所有前面的 URL: {"actionType":"navigate","actionUrl":
在下面的示例中,它将是https://www.ABCD.com
我正在使用python。最好是漂亮的汤。关于如何处理的想法?
</a>
<a aria-label="ABCD." class="we-lockup targeted-link l-column small-2 medium-3 large-2 we-lockup--shelf-align-top ember-view" data-metrics-click='{"actionType":"navigate","actionUrl":"https://www.ABCD.com","targetType":"card","targetId":"12345"}' data-metrics-location='{"locationType":"shelfCustomersAlsoBoughtMovie"}' href="https://www.ABCD.com" id="ember123"> <picture class="we-lockup__artwork we-artwork--lockup we-artwork--fullwidth we-artwork--vhs-movie-pic we-artwork ember-view" dir="ltr" id="ember123">
<noscript>
解决方案
dict
您可以使用内置模块将数据转换为 Python 字典 ( ) json
,然后访问actionUrl
密钥。
import json
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, "html.parser")
data = soup.find(
class_=
'we-lockup targeted-link l-column small-2 medium-3 large-2 we-lockup--shelf-align-top ember-view'
)['data-metrics-click']
json_data = json.loads(data)
print(type(json_data))
print(json_data['actionUrl'])
输出:
<class 'dict'>
https://www.ABCD.com
推荐阅读
- html - 如何在 django 模板中执行数学运算
- php - 如何从 influxdb 的数组 JSON 响应中获取 PHP 值
- java - spring data - 在对象中的数组中查询
- kubernetes - 可以在生产中使用 Kubernetes 自动缩放 v2beta2 作为 apiVersion 吗?
- javascript - 未捕获的 SyntaxError:JSON.parse:JSON 数据的第 1 行第 1 列的意外字符
- docker - How to ignore copying a environment variable file in a Dockerfile?
- javascript - 将 WooCommerce REST API 连接到 React Native
- java - 将文本文件中的数据存储到哈希图中
- angular - System.exit() 等效于角度?
- amazon-web-services - 在 nginx 服务器中为第三方工件创建私有仓库