python - 如何使用 Beautifulsoup 获取这些 Json 代码?

标签 python

JSON

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

我在 Python 中获取 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)

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

最佳答案

假设上面的脚本在字符串 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)

输出:

[
    {
        "key": "Owners",
        "bar": true,
        "values": [
            [
                1490400000000,
                1591,
                "",
                "",
                ""
            ],
            [
                1490486400000,
                1924,
                "#2B6A94",
                "",
                ""
            ],
            [
                1490572800000,
                1982,
                "",
                "",
                ""
            ],
            [
                1490659200000,
                1606,
                "",
                "",
                ""
            ]
        ]
    }
]

关于python - 如何使用 Beautifulsoup 获取这些 Json 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44733526/

相关文章:

python - Flask:设置应用程序和请求特定的属性?

python - 为什么这个 Pandas 系列函数不返回任何值?

python - 删除列表中的列表

python - 将 pandas 数据框按列分成两部分

python - Python 缺少 frozen-dict 类型的解决方法?

python - 在 Pandas 中按年份将日期分组在一起

迭代到大范围时出现 Python 内存错误

python 映射与字符串

python Docker 镜像 : How to execute multiple scripts at once?

python - 如何覆盖自定义模块的 ORM 方法取消链接?