python - 在 Python 中使用 BeautifulSoup 从 HTML 脚本标签中提取 JSON
问题描述
我有以下 HTML,我应该怎么做才能从变量中提取 JSON:window.__INITIAL_STATE__
<!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>
解决方案
You can use the following Python code to extract the JavaScript code.
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)
The JS code will be written to a file "temp.js". Then you can call node
to execute the JS file.
from subprocess import check_output
window_init_state = check_output(['node','temp.js'])
The python variable window_init_state
contains the JSON string of the JS object window.__INITIAL_STATE__
, which you can parse in python with JSONDecoder
.
Example
from subprocess import check_output
import json, bs4
html='''<!DOCTYPE doctype html>
<html lang="en">
<script> window.sessConf = "-2912474957111138742";
/* <sl:translate_json> */
window.__INITIAL_STATE__ = { 'Hello':'World'};
/* </sl:translate_json> */
</script>
</html>'''
soup = bs4.BeautifulSoup(html)
with open('temp.js','w') as f:
f.write('window = {};\n'+
soup.find('script').text.strip()+
';\nprocess.stdout.write(JSON.stringify(window.__INITIAL_STATE__));')
window_init_state = check_output(['node','temp.js'])
print(json.loads(window_init_state))
Output:
{'Hello': 'World'}
推荐阅读
- android - 我想在我的 recyclerview 中显示来自 URL 的图片
- laravel-8 - 未找到 Laravel 8 资源控制器 404
- javascript - iframe 中的表单未定义:边缘问题
- xsd - 如何根据 XSD 中的另一个字段值使字段成为必填项
- react-native - 调度带有 AxsiosError 的有效负载时的 Redux 状态突变
- firebase - 我应该在一个集合中有多个文档还是在一个文档中有多个对象/数组元素?
- c# - 为什么我的空 Avalonia 应用程序使用 100% CPU?
- java - 编译 jar 文件导致 ClassNotFoundException
- spring-boot - 使用 Zuul 在微服务中实现 SAML
- c# - 很想将我的有效负载序列化到 PredictionServiceClient 类?