如何使用python将html文件转换为json文件

2024-04-19 14:33:47 发布

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

我想从某个位置获取html文件,并使用python将其转换为Json格式。在

对于下面的代码,我得到的输出只是一个文本。在

from bs4 import BeautifulSoup
import json
html = '<p>Hello</p><p>world</p>'
soup = BeautifulSoup(html, 'html.parser')
things = soup.find_all(text=True)
print(things)

Tags: 文件代码from文本importjsonhelloworld
1条回答
网友
1楼 · 发布于 2024-04-19 14:33:47
 jsonD = json.dumps(htmlContent.text) converts the raw HTML content into a JSON 
 string representation. jsonL = json.loads(jsonD) parses the JSON string back into a 
 regular string/unicode object. This results in a no-op, as any escaping done by 
 dumps() is reverted by loads(). jsonL contains the same data as htmlContent.text.

 Try to use json.dumps to generate your final JSON instead of building the JSON by 
 hand:

 ContentUrl = json.dumps({
'url': str(urls),
'uid': str(uniqueID),
'page_content': htmlContent.text,
'date': finalDate
})

相关问题 更多 >