You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用BeautifulSoup提取`data-amount`属性下的JSON数据?

相关页面元素截图

实现方法

你已经成功定位到了携带目标属性的span.price-data标签,只需要补充属性读取和JSON解析逻辑即可,修改后的可运行代码如下:

import requests
import json
from bs4 import BeautifulSoup

url = "https://azure.microsoft.com/en-au/pricing/details/managed-disks/"
response = requests.get(url)
table_doc = BeautifulSoup(response.text, "html.parser")
data = []

# 定位目标表格
table = table_doc.find_all(
    "table", attrs={"class": "data-table__table data-table__table--pricing"}
)[0]

table_body = table.find("tbody")
rows = table_body.find_all("tr")

for row in rows:
    cols = row.find_all("td")
    res = row.find("span", attrs={"class": "price-data"})
    # 避免无对应标签时报错
    if not res:
        continue
    # 读取data-amount自定义属性
    amount_json_str = res.get("data-amount")
    # 解析为Python可操作的JSON对象
    amount_data = json.loads(amount_json_str)
    print(amount_data)
    data.append(amount_data)

关键逻辑说明

  • BeautifulSoup标签对象的get()方法可以安全读取自定义属性,属性不存在时会返回None,不会直接抛出异常
  • 读取到的data-amount值为字符串格式,符合JSON规范时调用json.loads()即可转为字典/列表类型,方便后续处理

内容的提问来源于stack exchange,提问作者John Pham

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 03:36:03