You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用PowerShell从含JSON的HTML响应中提取ad_user对应ID值

你可以通过正则匹配提取var data =后的JSON内容,再解析筛选目标ID,修改后的完整代码如下:

$cred = "[my unique token]"
$headers = @{ 
    Authorization = "Bearer $cred"
    # 优先请求JSON格式,符合接口注释提示,避免返回HTML
    Accept = "application/json"
}

$response = Invoke-WebRequest -Method Get -Headers $headers -Uri "[my URL]"
$content = $response.Content

# 兼容两种响应格式:优先直接解析JSON,失败则从HTML提取内嵌JSON
try {
    $dataObj = $content | ConvertFrom-Json -ErrorAction Stop
}
catch {
    # 正则匹配script标签内的data字段值
    if ($content -match 'var data = (\{.*?\})(?=\s*[,;]?\s*</script>)') {
        $jsonRaw = $matches[1] -replace ',\s*([\]}])', '$1' # 修复样例中JSON末尾多余逗号的语法问题
        $dataObj = $jsonRaw | ConvertFrom-Json
    }
    else {
        throw "未找到目标内嵌数据"
    }
}

# 筛选目标ID并剔除前缀
$targetIds = $dataObj.ID | Where-Object { $_ -like 'ad_user://*' } | ForEach-Object { $_ -replace '^ad_user://', '' }

# 输出最终结果
$targetIds

关键修改说明

  • 请求头新增Accept: application/json配置,优先触发接口返回纯JSON格式,减少解析成本
  • 增加异常兼容逻辑:如果接口依然返回HTML,会自动提取内嵌的JSON片段,同时兼容了非标准JSON末尾多余逗号的场景
  • 最后通过通配符匹配筛选前缀为ad_user://的ID,用正则替换剔除前缀得到目标值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 11:54:07