首页 > 解决方案 > 使用 BeautifulSoup 解析脚本标签内的 json 文本

问题描述

我正在尝试使用 BeautifulSoup 提取 Python3@context中 ( ) 元素中的文本。'script', type='application/ld+json'

我在一页中有多个脚本,我想获得上面 json 中列出的特定功能。

我尝试使用此代码:

data = soup.find_all('script', type='application/ld+json')
print(data)

这给了我所有脚本的完整提取内容,但我想在每个脚本的上下文中获得一个特定的功能。

功能示例:

{"name":"test","telephone":"600.212.0000","url":"https://test.com/test"}

对于这个例子,我想得到"url"零件。

有人知道用 Python 做吗?

非常感谢您的帮助。

标签: pythonjsonweb-scrapingbeautifulsoupfindall

解决方案


您可以使用列表推导get()

data = soup.find_all('script', type='application/ld+json')

urls = [i.get('url') for i in data]

推荐阅读