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

如何用DOM Parser获取第三个script标签内容及遍历所有script标签

解决Script标签的内容获取与遍历问题

1. 使用DOM Parser获取第三个script标签内容

如果是处理外部HTML字符串(非当前页面DOM),可通过DOMParser解析后定位目标标签:

// 替换为你的HTML字符串
const htmlStr = `<p>我想要用forEach循环获取所有script标签</p><script id="wiz_jd" nonce="TPwfWuzY1BHxa72M4FPOew">
    if (window['_wjdc']) {const wjd = {}; window['_wjdc'](wjd); delete window['_wjdc'];}
</script>
<script aria-hidden="true" id="WIZ-footer" nonce="TPwfWuzY1BHxa72M4FPOew">
    window.wiz_progress&&window.wiz_progress(); window.stopScanForCss&&window.stopScanForCss(); ccTick('bl');
</script>
<script nonce="TPwfWuzY1BHxa72M4FPOew">"https://video-downloads.googleusercontent.com/..."</script>`;

const parser = new DOMParser();
const doc = parser.parseFromString(htmlStr, 'text/html');
// 第三个script对应索引为2(NodeList从0开始计数)
const thirdScript = doc.querySelectorAll('script')[2];
const thirdScriptContent = thirdScript.textContent.trim();
console.log(thirdScriptContent);

如果是在当前页面直接获取,无需DOMParser,直接操作document:

const thirdScript = document.querySelectorAll('script')[2];
const thirdScriptContent = thirdScript.textContent.trim();
console.log(thirdScriptContent);

2. 使用forEach遍历所有script标签

document.querySelectorAll('script')返回NodeList对象,支持两种遍历方式:

方式一:直接调用NodeList的forEach方法(现代浏览器兼容)

document.querySelectorAll('script').forEach((script, index) => {
  console.log(`第${index + 1}个script内容:`, script.textContent.trim());
  // 可额外获取标签属性,比如id、nonce
  console.log(`标签ID:${script.id},nonce值:${script.nonce}`);
});

方式二:转为数组后遍历(兼容旧版浏览器)

Array.from(document.querySelectorAll('script')).forEach((script, index) => {
  console.log(`第${index + 1}个script内容:`, script.textContent.trim());
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 10:15:53