如何使用beauthulsoup获取这些Json代码?

2024-10-02 02:33:33 发布

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

JSON格式 在

 <script>
 var data2sales= 
 [{
   "key": "Owners",
   "bar": true,
   "values": [
     [1490400000000, 1591, "", "", ""],
     [1490486400000, 1924, "#2B6A94", "", ""],
     [1490572800000, 1982, "", "", ""],
     [1490659200000, 1606, "", "", ""]]
 }]
 </script>

我在Python中获取Json的代码 在

^{pr2}$

我是Python中BeautifulSoup的新手,我试图从BeautifulSoup中提取一个dict。正如您在我的代码中看到的,我用python重新生成了JSON代码,并保存在newDict变量中。但它不起作用。有没有人可以教我如何提取JSON代码?谢谢您。在


Tags: key代码jsontruevar格式scriptbar
1条回答
网友
1楼 · 发布于 2024-10-02 02:33:33

假设上面的脚本在一个字符串text内,可以执行如下操作:

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)

输出:

^{pr2}$

相关问题 更多 >

    热门问题