You need to enable JavaScript to run this app. 如何从fetch请求返回的HTML文本中提取内嵌JavaScript变量
优惠活动
大模型
产品
解决方案
定价
更多

如何从fetch请求返回的HTML文本中提取内嵌JavaScript变量

从fetch返回的HTML文本提取内嵌JS变量的实现方案

方案1:正则提取(适合变量定义格式固定的简单场景)

如果目标变量的赋值格式固定(如统一为单/双引号包裹的字符串,无复杂表达式),可直接通过正则匹配变量声明语句提取值。
匹配逻辑需兼容变量声明前后的冗余空白、单双引号两种赋值格式,对应正则规则:

// 匹配varAPI的正则
/var varAPI\s*=\s*['"](.*?)['"]\s*;/

补全后的完整实现代码:

fetch("https://testwebsite.com", {})
  .then(response => response.text())
  .then(result => {
     // 提取varAPI,匹配失败返回null兜底
     const varAPIMatch = result.match(/var varAPI\s*=\s*['"](.*?)['"]\s*;/);
     const varAPI = varAPIMatch ? varAPIMatch[1] : null;

     // 提取anotherVAR
     const anotherVARMatch = result.match(/var anotherVAR\s*=\s*['"](.*?)['"]\s*;/);
     const anotherVAR = anotherVARMatch ? anotherVARMatch[1] : null;

     // 可对提取到的变量做后续业务处理
     console.log('提取到的varAPI:', varAPI);
     console.log('提取到的anotherVAR:', anotherVAR);

     // 原代码中的`$result`为笔误,返回原始响应或处理后的数据即可
     return result;
  })
  .then(result => console.log(result))
  .catch(error => console.log('error', error));

方案2:DOMParser解析(更稳定,适配复杂场景)

如果目标页面结构复杂、存在多处同名字符串,正则直接匹配全局HTML容易出现误判,可先将HTML文本解析为DOM对象,仅从对应script标签的内容中提取变量,避免误匹配。
补全后的完整实现代码(浏览器环境原生支持DOMParser):

fetch("https://testwebsite.com", {})
  .then(response => response.text())
  .then(result => {
     // 初始化DOM解析器
     const parser = new DOMParser();
     const doc = parser.parseFromString(result, 'text/html');
     // 定位到包含目标变量的script标签
     const targetScript = Array.from(doc.querySelectorAll('script'))
       .find(script => script.textContent.includes('var varAPI') && script.type === 'text/javascript');
     const scriptContent = targetScript?.textContent || '';

     // 仅从脚本内容中执行正则匹配,避免误伤页面其他位置的同名字符串
     const varAPIMatch = scriptContent.match(/var varAPI\s*=\s*['"](.*?)['"]\s*;/);
     const varAPI = varAPIMatch ? varAPIMatch[1] : null;

     const anotherVARMatch = scriptContent.match(/var anotherVAR\s*=\s*['"](.*?)['"]\s*;/);
     const anotherVAR = anotherVARMatch ? anotherVARMatch[1] : null;

     console.log('提取到的varAPI:', varAPI);
     console.log('提取到的anotherVAR:', anotherVAR);

     return result;
  })
  .then(result => console.log(result))
  .catch(error => console.log('error', error));

注意事项

  • 如果目标变量的赋值不是简单字符串(如数字、对象、数组),需要调整正则规则,匹配到变量声明后的分号前内容即可。
  • 禁止直接用eval执行整段脚本内容,避免目标页面的恶意代码触发安全风险。
  • 若运行环境为Node.js,需要引入DOM模拟模块才能使用DOMParser能力。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.18 10:57:04