Python 如何使用Beautifulsoup获取这些Json代码?
JSONPython 如何使用Beautifulsoup获取这些Json代码?,python,Python,JSON 我是Python中BeautifulSoup的新手,我正在尝试从BeautifulSoup中提取一个dict。正如您在我的代码中看到的,我用python重新编写了JSON代码,并保存在newDict变量中。但它不起作用。有没有人可以教我,如何提取JSON代码?谢谢。假设上面的脚本位于字符串文本中,您可以执行以下操作: notices = str(soup.select('script')[30]) split_words=notices.split('var data2sales
我是Python中BeautifulSoup的新手,我正在尝试从BeautifulSoup中提取一个
dict
。正如您在我的代码中看到的,我用python重新编写了JSON代码,并保存在newDict变量中。但它不起作用。有没有人可以教我,如何提取JSON代码?谢谢。假设上面的脚本位于字符串文本中,您可以执行以下操作:
notices = str(soup.select('script')[30])
split_words=notices.split('var data2sales= ')
split_words=split_words[1]
temp=split_words[44:689]
temp = 'var data2sales= {' +temp + '}'
print(temp)
newDict = json.loads((temp))
print(newDict)
输出:
import json
from bs4 import BeautifulSoup
soup = BeautifulSoup(text, 'html.parser')
script_text = soup.find('script').get_text()
relevant = script_text[script_text.index('=')+1:] #removes = and the part before it
data = json.loads(relevant) #a dictionary!
print json.dumps(data, indent=4)
我只是使用len(eval(data.get_text())['data']['song']['list'])
你好。请澄清什么是不起作用的(输出和stacktrace),并提供一段代码,通过该代码问题是可复制的(从您的原始代码复制和过去的代码不能独立工作)。啊,我明白了。感谢是否会true
导致名称错误
?Python的True
是大写的,JavaScript不是。@Jules不,不会。通常,我使用的JSON包含null
值,而不是None
值。此外,以上是实际输出,因此没有错误。
import json
from bs4 import BeautifulSoup
soup = BeautifulSoup(text, 'html.parser')
script_text = soup.find('script').get_text()
relevant = script_text[script_text.index('=')+1:] #removes = and the part before it
data = json.loads(relevant) #a dictionary!
print json.dumps(data, indent=4)
[
{
"key": "Owners",
"bar": true,
"values": [
[
1490400000000,
1591,
"",
"",
""
],
[
1490486400000,
1924,
"#2B6A94",
"",
""
],
[
1490572800000,
1982,
"",
"",
""
],
[
1490659200000,
1606,
"",
"",
""
]
]
}
]