我有一个HTML文件,我可以用Python卷曲和下载。但是,我不知道如何从中获得我想要的数据。我用BS从XML文件中获取值,但从来没有这样的东西。以下是我试图阅读和获取的文件部分:
<script>
var AC = {};
AC.org_json =
{
"id": "manager",
"children": [
{
"id": "employee1",
"children": [],
"data": {
"direct_reports": 0,
"badge_color": "F",
"badge_url": "https://someurl",
"full_name": "Employee1 Name",
"job_title": "Employee Job Title",
"department_name": "IT",
"building": "SITE1",
"phone": null,
"expanded": false
}
},
{
"id": "employee2",
"children": [],
"data": {
"direct_reports": 0,
"badge_color": "F",
"badge_url": "https://someurl",
"full_name": "Employee2 Name",
"job_title": "Employee Job Title",
"department_name": "IT",
"building": "SITE1",
"phone": null,
"expanded": false
}
},
......continues for however many entries there are.
</script>
目标是获取每个条目的“id”和“职务”。我只是需要一些帮助,从正确的方向开始。感谢您的帮助。非常感谢。你知道吗
编辑: 我能够从HTML文件中分离出标签中的数据。你知道吗
from bs4 import BeautifulSoup
#opens data file
get_data = open(html,'r').read()
soup = BeautifulSoup(get_data)
title = soup.find("div", id="content")
json_data = title.find_next("script")
print json_data
它给出了上面的精确输出。下一个问题是如何从这些数据中获取值? 如果我这样做了:
data = json.loads(json_data)
print data
然后我得到:ValueError: No JSON object could be decoded
我会这么做:
soup.find_all('script')
获取所有脚本标记。你知道吗json.loads()
,然后从dictionary获取返回的值。你知道吗如果你知道只有一个脚本标签,#3很简单。如果可能有其他脚本块包含大量的非jsonjavascript,那么通常需要使用一些regex或try/catch块,因为如果传递一个非JSON的字符串,try/catch块可能会出错。你知道吗
您正试图从另一种语言(HTML)中解析javascript字典(JSON),因此理想情况下,您可以使用真正的解析器加载HTML,然后使用真正的解析器加载javascript,但是如果您完全了解自己的文件格式,那么您可以修改一些regex来删除除JSON之外的所有内容,然后使用json.loads文件()将其解析为python字典。你知道吗
相关问题 更多 >
编程相关推荐