Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sql-server-2005/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用Beautifulsoup获取这些Json代码?_Python - Fatal编程技术网

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

Python 如何使用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

JSON


我是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,
                "",
                "",
                ""
            ]
        ]
    }
]