首页 > 解决方案 > 使用beautifulsoup查找没有标签的json对象

问题描述

假设我们有以下

<title> Hello world! </title>
<span class="something">Here is some text</span>
{foo:{bar:1},alpha:2,beta:{donkey:horse}}

我想在python中提取字典/json对象。由于它不在标签中,因此我很难soup.find_all以一种简单的方式使用它 - 是使用正则表达式的最佳方式,还是有更好的主意?请注意,dict 可以在网页上的任何位置,即并不总是作为网页上的最后一部分

标签: pythonbeautifulsoup

解决方案


你可以尝试这样的事情。假设“beta”是每个 json 对象

h = ''''<title> Hello world! </title>
<span class="something">Here is some text</span>
{foo:{bar:1},alpha:2,beta:{donkey:horse}}'''
soup = BeautifulSoup(h, "html.parser")
soup.find_all(string=re.compile('beta'))

这是输出(列表)。分页符很可能来自如何将其作为字符串读取。

['\n{foo:{bar:1},alpha:2,beta:{donkey:horse}}']

推荐阅读