使用Python提取Script标签中的JSON数据

在网页开发中,经常会将JSON数据存储在<script>标签中。本文将介绍如何使用Python提取这些JSON数据。

步骤:

  1. 导入json模块:

    import json
    
  2. 获取包含JSON数据的<script>标签内容: 可以使用网页抓取库(如Beautiful Soup)或正则表达式提取<script>标签内容。

  3. 提取JSON字符串:

    script = '''
    <script>
        var data = {'name': 'John', 'age': 30, 'city': 'New York'};
    </script>
    '''
    
    start_index = script.find('{')  # 查找JSON数据的起始位置
    end_index = script.find('}') + 1  # 查找JSON数据的结束位置(加1是为了包含右括号)
    json_data = script[start_index:end_index]  # 提取JSON数据
    
  4. 解析JSON数据:

    data = json.loads(json_data)
    
  5. 使用提取的数据:

    print(data)
    print(data['name'])  # 访问JSON对象的属性
    

完整代码示例:

import json

script = '''
<script>
    var data = {'name': 'John', 'age': 30, 'city': 'New York'};
</script>
'''

start_index = script.find('{')
end_index = script.find('}') + 1
json_data = script[start_index:end_index]

data = json.loads(json_data)

print(data)
print(data['name'])

输出结果:

{'name': 'John', 'age': 30, 'city': 'New York'}
John

注意事项:

  • 此方法假设<script>标签中只包含一个JSON数据,并且该数据是有效的JSON格式。
  • 如果<script>标签中包含多个JSON数据,您可能需要进行适当的处理,例如使用正则表达式提取所有JSON字符串。
  • 在实际应用中,建议使用网页抓取库来提取<script>标签内容,以便更好地处理HTML结构和错误处理。
Python提取Script标签中JSON数据教程

原文地址: http://www.cveoy.top/t/topic/fbPF 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录