如何使用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
相关产品推荐
相关产品推荐

