如何从html、json中提取标记?

2024-04-18 20:50:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个json文件,我需要从json文件中提取某些html标记

下面我有一个提示……`

enter image description here


Tags: 文件标记jsonhtml
1条回答
网友
1楼 · 发布于 2024-04-18 20:50:24

您可以尝试以下方法:

try:
    from BeautifulSoup import BeautifulSoup
except ImportError:
    from bs4 import BeautifulSoup

#example of json data (dictionary)
data = {
    "url":"www.example.com",
    "content" : "<!DOCTYPE html><html><body><h1>My First Heading</h1><strong>My first paragraph.</strong></body></html>"
}

#html parser
soup = BeautifulSoup(data["content"], "html.parser")

#get all the tags of one type
print(soup.find_all("h1"))
print(soup.find_all("strong"))

您将得到一个标签列表,如:

[<h1>My First Heading</h1>]
[<strong>My first paragraph.</strong>]

要安装bs4,请执行以下操作:

pip install bs4

我希望有帮助

相关问题 更多 >