You need to enable JavaScript to run this app. Python按键值解析HTML提取目标数组并后续转换为JSON的方法
优惠活动
大模型
产品
解决方案
定价
更多

Python按键值解析HTML提取目标数组并后续转换为JSON的方法

Python实现提取HTML中内嵌脚本的目标JSON数据

依赖安装

首先安装所需第三方库:

pip install beautifulsoup4 lxml

完整实现代码

from bs4 import BeautifulSoup
import re
import json

# 此处替换为实际的完整HTML内容,也可通过requests等爬虫库获取
html_content = """
填入你的HTML文本
"""

# 1. 解析HTML提取目标script标签
soup = BeautifulSoup(html_content, 'lxml')
target_script = None
# 匹配带指定类名的body节点
body = soup.find('body', class_=['browser-chrome', 'os-windows', 'is-withMagicUnderlines', 'v-unbound', 'v-glyph', 'v-glyph--m2-unbound', 'is-noJs'])
if body:
    # 筛选body下不带src属性的内嵌script标签
    scripts = body.find_all('script', src=False)
    for script in scripts:
        script_text = script.string
        if script_text and 'obvInit' in script_text:
            target_script = script_text
            break

if not target_script:
    raise ValueError("未找到符合要求的目标script标签")

# 清理CDATA标记(如果存在)
target_script = target_script.replace('// <![CDATA[', '').replace('// ]]>', '')

# 2. 提取obvInit方法的入参JSON字符串
# 正则适配多空格、换行场景
match = re.search(r'window\s*\["obvInit"\]\s*\(\s*(\{.*?\})\s*\)', target_script, re.DOTALL)
if not match:
    raise ValueError("未匹配到obvInit方法的入参数据")
json_raw = match.group(1)

# 3. 转换为Python字典并提取value数组
data = json.loads(json_raw)
# 按指定路径获取value数组
value_array = data['references']['Collection']['1']['value']

# 输出结果,可直接后续使用或转JSON存储
print(json.dumps(value_array, ensure_ascii=False, indent=2))

注意事项

  • 如果Collection下的键名不是固定的"1",可以遍历data['references']['Collection'].values()获取所有集合对象后再提取对应value
  • 正则匹配使用re.DOTALL参数,允许.匹配换行符,适配多行JSON的场景
  • 如果返回的JSON存在转义异常,可先对json_raw做额外的转义字符清理后再执行json.loads

内容的提问来源于stack exchange,提问作者Eliran Turgeman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.10 19:12:02