用Python中的BeautifulSoup从HTML脚本标记中提取JSON

用Python中的BeautifulSoup从HTML脚本标记中提取JSON,python,html,json,beautifulsoup,Python,Html,Json,Beautifulsoup,我有下面的HTML,我应该怎么做才能从变量中提取JSON:window.\uuuu INITIAL\u STATE\uuuuu <!DOCTYPE doctype html> <html lang="en"> <script> window.sessConf = "-2912474957111138742"; /* <sl:translate_json> */

我有下面的HTML,我应该怎么做才能从变量中提取JSON:
window.\uuuu INITIAL\u STATE\uuuuu

<!DOCTYPE doctype html>

<html lang="en">
<script>
                  window.sessConf = "-2912474957111138742";
                  /* <sl:translate_json> */
                  window.__INITIAL_STATE__ = { /* Target JSON here with 12 million characters */};
                  /* </sl:translate_json> */
                </script>
</html>

window.sessConf=“-2912474957111138742”;
/*  */
window.\uuuu INITIAL\u STATE\uuuuu={/*目标JSON,此处包含1200万字符*/};
/*  */

您可以使用以下Python代码来提取JavaScript代码

soup = BeautifulSoup(html)
s=soup.find('script')
js = 'window = {};\n'+s.text.strip()+';\nprocess.stdout.write(JSON.stringify(window.__INITIAL_STATE__));'
with open('temp.js','w') as f:
    f.write(js)
JS代码将被写入一个文件“temp.JS”。然后可以调用
节点
来执行JS文件

from subprocess import check_output
window_init_state = check_output(['node','temp.js'])
python变量
window\u init\u state
包含JS对象
window.\uu INITIAL\u state\uuu
的JSON字符串,您可以使用
JSONDecoder
在python中解析该字符串

例子
来自子流程导入检查\u输出
导入json,bs4
html=“”
window.sessConf=“-2912474957111138742”;
/*  */
窗口。uuu初始状态uuu={'Hello':'World'};
/*  */
'''
soup=bs4.BeautifulSoup(html)
以open('temp.js','w')作为f:
f、 写入('window={};\n'+
soup.find('script').text.strip()+
“;\nprocess.stdout.write(JSON.stringify(window.\uu INITIAL\u STATE\uuuu))”)
window_init_state=检查_输出(['node','temp.js'])
打印(json.load(窗口初始化状态))
输出:

{'Hello': 'World'}

gdlmx的代码是正确的,非常有用

from subprocess import check_output
soup = BeautifulSoup(html)
s=soup.find('script')
js = 'window = {};\n'+s.text.strip()+';\nprocess.stdout.write(JSON.stringify(window.__INITIAL_STATE__));'
window_init_state = check_output(['node','temp.js'])
类型(窗口初始化状态)将为。因此,您应该使用以下代码

jsonData= window_init_state.decode("utf-8")

到目前为止,您尝试了什么?1200万字符的json是否都在一行中?这将大大简化答案。@JeffUK我尝试从脚本标记获取所有文本,然后拆分('\n'),但它以某种方式将JSON拆分为两个子字符串。@solarc是的,它是单行JSON。您的系统中有
nodejs
吗?我得到:FileNotFoundError:[WinError 2]系统无法从check_输出中找到指定的文件。它可能是由open('temp.js','w')作为f引起的吗?这可能是因为程序
节点
不包含在
路径
环境变量中。您是否成功安装了它?如果您不确定
nodejs
安装在何处。您可以在列出的位置查找。我还有一个问题,有没有办法避免将js文件写入硬盘,但实现相同的目标?是的。尝试使用
check\u输出(['node','-e',您的\u-js\u脚本])
其中
您的\u-js\u脚本
是包含js脚本的python字符串变量。