gpt4 book ai didi

python - 使用 Python 格式化 HTML 到 JSON

转载 作者:行者123 更新时间:2023-12-01 00:01:39 25 4
gpt4 key购买 nike

我在网上看到了几个关于如何将 HTML 内容转换为 JSON 的示例,但我无法获得实际结果。

假设我有以下 html_content:

<html>
<body>
<h1>My Heading</h1>
<p>Hello world</p>
<table>
<tr>
<th>Name</th>
<th>Age</th>
<th>License</th>
<th>Amount</th>
</tr>
<tr>
<td>John</td>
<td>28</td>
<td>Y</td>
<td>12.30</td>
</tr>
<tr>
<td>Kevin</td>
<td>25</td>
<td>Y</td>
<td>22.30</td>
</tr>
<tr>
<td>Smith</td>
<td>38</td>
<td>Y</td>
<td>52.20</td>
</tr>
<tr>
<td>Stewart</td>
<td>21</td>
<td>N</td>
<td>3.80</td>
</tr>
</table>
</body>
</html>

如您所见,它包含标题、段落和表格元素。我正在尝试将上述内容转换为 JSON 并将结果输出到一个单独的文件,并使用正确格式。这是我的代码:

import sys
import json
jsonD = json.dumps(html_content, sort_keys=True, indent=4)

sys.stdout=open("output.json","w")
print (jsonD)
sys.stdout.close()

结果是:

"\n<html>\n\t<body>\n\t\t<h1>My Heading</h1>\n\t\t<p>Hello world</p>\n\t\t<table>\n\t\t\t<tr>\n\t\t\t\t<th>Name</th>\n\t\t\t\t<th>Age</th>\n\t\t\t\t<th>License</th>\n\t\t\t\t<th>Amount</th>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td>John</td>\n\t\t\t\t<td>28</td>\n\t\t\t\t<td>Y</td>\n\t\t\t\t<td>12.30</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td>Kevin</td>\n\t\t\t\t<td>25</td>\n\t\t\t\t<td>Y</td>\n\t\t\t\t<td>22.30</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td>Smith</td>\n\t\t\t\t<td>38</td>\n\t\t\t\t<td>Y</td>\n\t\t\t\t<td>52.20</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td>Stewart</td>\n\t\t\t\t<td>21</td>\n\t\t\t\t<td>N</td>\n\t\t\t\t<td>3.80</td>\n\t\t\t</tr>\n\t\t</table>\n\t</body>\n</html>\n"

如您所见,结果没有转义任何回车符或制表符,并且使输出看起来像一个长字符串。如何纠正此问题,以便从 JSON 角度正确格式化输出?

最佳答案

您需要知道您希望 json 输出是什么样子。如果您希望名称作为键,值作为其他所有内容的列表,我会这样做:

from bs4 import BeautifulSoup
import json

html_content = """
<table>
<tr>
<td>John</td>
<td>28</td>
<td>Y</td>
<td>12.30</td>
</tr>
<tr>
<td>Kevin</td>
<td>25</td>
<td>Y</td>
<td>22.30</td>
</tr>
<tr>
<td>Smith</td>
<td>38</td>
<td>Y</td>
<td>52.20</td>
</tr>
<tr>
<td>Stewart</td>
<td>21</td>
<td>N</td>
<td>3.80</td>
</tr>
</table>
<h1> hello world <h1>
<table>
<tr>
<td>Jack</td>
<td>1</td>
</tr>
<tr>
<td>Joe</td>
<td>2</td>
</tr>
<tr>
<td>Bill</td>
<td>3</td>
</tr>
<tr>
<td>Sam</td>
<td>4</td>
</tr>
</table>
"""

html_content_parsed = [[cell.text for cell in row("td")]
for row in BeautifulSoup(html_content,features="html.parser")("tr")]

html_content_dictionary = {element[0]:element[1:] for element in html_content_parsed}

print(json.dumps(html_content_dictionary, indent=4))

如您所见,这将忽略其他非表格元素并将所有表格放入 json 中。

htmltojson_program_output

您可以在此处试用该程序: https://repl.it/@Mandawi/htmltojson

关于python - 使用 Python 格式化 HTML 到 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60304382/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com