【问题标题】:How can I extract this JSON data under `data-amount` using BeautifulSoup?如何使用 BeautifulSoup 在“数据量”下提取此 JSON 数据?
【发布时间】:2021-12-01 12:44:41
【问题描述】:

如何使用 BeautifulSoup 获取data-amount 下的 JSON 数据?

这是我尝试过的:

import requests
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"})
    print(res)

【问题讨论】:

    标签: python json beautifulsoup


    【解决方案1】:

    您可以通过使用[<attribute-name>] 访问data-amount 属性 来访问JSON 数据。在您的示例中:

    res = row.find('span', attrs={'class':'price-data'})["data-amount"]
    

    此外,您可以将 JSON 数据(变量 res)转换为字典 (dict),您可以在其中使用内置的 json 模块访问 key/values

    import json
    ...
    
    res = json.loads(row.find('span', attrs={'class':'price-data'})["data-amount"])
    print(res)  #  `<class 'dict'>`
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-29
      • 1970-01-01
      • 2019-05-24
      • 1970-01-01
      相关资源
      最近更新 更多