Python 将 html 源代码转换为 json 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43469412/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert html source code to json object
提问by Umesh Kaushik
I am fetching html source code of many pages from one website, I need to convert it into json object and combine with other elements in json doc. . I have seen many questions on same topic but non of them were helpful.
我正在从一个网站获取多个页面的 html 源代码,我需要将其转换为 json 对象并与 json doc 中的其他元素结合。. 我看过很多关于同一主题的问题,但没有一个是有帮助的。
My code:
我的代码:
url = "https://totalhash.cymru.com/analysis/?1ce201cf28c6dd738fd4e65da55242822111bd9f"
htmlContent = requests.get(url, verify=False)
data = htmlContent.text
print("data",data)
jsonD = json.dumps(htmlContent.text)
jsonL = json.loads(jsonD)
ContentUrl='{ \"url\" : \"'+str(urls)+'\" ,'+"\n"+' \"uid\" : \"'+str(uniqueID)+'\" ,\n\"page_content\" : \"'+jsonL+'\" , \n\"date\" : \"'+finalDate+'\"}'
above code gives me unicode type, however, when I put that output in jsonLint it gives me invalid json error. Can somebody help me understand how can I convert the complete html into a json objet?
上面的代码给了我 unicode 类型,但是,当我将该输出放入 jsonLint 时,它给了我无效的 json 错误。有人可以帮助我了解如何将完整的 html 转换为 json 对象吗?
回答by cg909
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
.
jsonD = json.dumps(htmlContent.text)
将原始 HTML 内容转换为 JSON 字符串表示形式。
jsonL = json.loads(jsonD)
将 JSON 字符串解析回常规字符串/unicode 对象。这会导致无操作,因为由 完成的任何转义都由dumps()
恢复loads()
。jsonL
包含与 相同的数据htmlContent.text
。
Try to use json.dumps
to generate your final JSON instead of building the JSON by hand:
尝试使用json.dumps
生成最终的 JSON 而不是手动构建 JSON:
ContentUrl = json.dumps({
'url': str(urls),
'uid': str(uniqueID),
'page_content': htmlContent.text,
'date': finalDate
})
回答by behzad mehrabi
You can use tojson module, easy and readable :)
您可以使用 tojson 模块,简单易读:)
python3 -m pip install tojson --user
python3 -m pip install tojson --user