python如何将script中的json数据提取出来
您可以使用Python的json模块来提取script中的json数据。以下是一个简单的示例:
import json
# 假设script中的json数据存储在变量data中
script = """
<script>
var data = {"name": "John", "age": 30, "city": "New York"};
</script>
"""
# 提取script中的json数据
start_index = script.find('{') # 查找json数据的起始位置
end_index = script.find('}') + 1 # 查找json数据的结束位置(加1是为了包含右括号)
json_data = script[start_index:end_index] # 提取json数据
# 解析json数据
data = json.loads(json_data)
# 打印提取的json数据
print(data)
输出结果:
{'name': 'John', 'age': 30, 'city': 'New York'}
请注意,此方法假设script中只包含一个json数据,并且该数据是有效的。如果script中包含多个json数据,您可能需要进行适当的处理。
原文地址: https://www.cveoy.top/t/topic/jbPA 著作权归作者所有。请勿转载和采集!