【问题标题】:Parsing application ld+Json with Beautifulsoup (findAll)使用 Beautifulsoup (findAll) 解析应用程序 ld+Json
【发布时间】:2021-09-28 07:38:32
【问题描述】:

我目前的问题是我想解析一个网站的应用程序 JSON 数据。但是该网站有多个带有应用程序数据的脚本标签,我试图将它们全部获取,而不仅仅是一个。 我目前正在努力让它发挥作用。我有以下代码:

return json.loads("".join(soup.findAll("script", {"type":"application/ld+json"})[1]))

是否有人知道如何摆脱列表索引 ([1]) 并使用 findAll 打印出字典中的每个 JSON 数据?当我删除 [1] 时,我收到以下错误:

sequence item 0: expected str instance, Tag found

完整代码:

def get_ld_json(url: str) -> dict: 
  parser = "html.parser"
  req = requests.get(url)
  soup = BeautifulSoup(req.text, parser)
  return json.loads("".join(soup.findAll("script", {"type":"application/ld+json"})[1]))

【问题讨论】:

  • script 标签包含 javascript,而不是 JSON。我还没有看到只有 JSON 数据的(有用的)script 标签,但我想看一些。
  • 你可以看看这个答案:stackoverflow.com/a/14264141/4476484。你可以试试join([str(x) for x in your_list])
  • 可以分享网址吗?
  • chefkoch.de/rezepte/1346961239454700/… ,我正在尝试解析配方数据,正如您在 quellcode 中看到的那样,有两个应用程序 ld+json 脚本。我想把这两个都放在一个字典里,因为其他网站(我也想用脚本解析)只有一个应用程序 ld+json。

标签: python json parsing beautifulsoup


【解决方案1】:

您不能将多个 JSON 对象转换为一个,否则会使 JSON 无效。

可以做的是创建一个包含所有 JSON 对象的 list,然后遍历列表以获取正确的数据。

import json
import requests
from bs4 import BeautifulSoup


url = "https://www.chefkoch.de/rezepte/1346961239454700/Geschnetzeltes-Schweinefilet-in-Senfsahne.html"

soup = BeautifulSoup(requests.get(url).content, "html.parser")
data = [
    json.loads(x.string) for x in soup.find_all("script", type="application/ld+json")
]

例如,要获取 names,请遍历列表 (data) 并访问“name”键:

for d in data:
    print(d["name"])

哪些输出:

Chefkoch
Geschnetzeltes Schweinefilet in Senfsahne

【讨论】:

  • 首先,感谢您的帮助:)。对于键“名称”,它的效果很好,但是当我搜索键“recipeIngredient”时,它会给出一个 KeyError :/。你知道为什么吗?
  • @Broump 那是因为 first 字典没有那个键。您可以使用.get() 代替["key"]。例如:for d in data print(d.get("recipeIngredient", ""))
  • 非常感谢!!现在它可以工作了:D,祝你有美好的一天;)
猜你喜欢
  • 2018-12-02
  • 1970-01-01
  • 2017-09-25
  • 2016-10-02
  • 2020-03-06
  • 1970-01-01
  • 2020-11-22
  • 2019-11-26
  • 1970-01-01
相关资源
最近更新 更多