在 JavaScript 中,如果你想获取 原始文本值(非标准化/未解析的 URL),而不是通过 getAttribute
返回的标准化 URL,可以使用以下方法:
1. 直接获取属性文本值
使用 element.getAttribute('href')
(或其他属性名)时,浏览器会自动标准化 URL(比如补全相对路径)。要获取原始文本值,可以:
方法 1:通过 attributes
对象
const element = document.querySelector('a');
const rawHref = element.attributes.href.nodeValue; // 原始文本值
方法 2:直接读取 outerHTML
并解析
如果元素是动态生成的:
const element = document.querySelector('a');
const outerHTML = element.outerHTML;
// 用正则提取 href(示例)
const rawHref = outerHTML.match(/href="(.*?)"/)[1];
2. Cheerio(Node.js环境)获取原始URL
在 Cheerio 中,默认不会标准化 URL,直接 .attr()
就是原始值:
const cheerio = require('cheerio');
const html = '<a href="../page.html#anchor">Link</a>';
const $ = cheerio.load(html);
const rawHref = $('a').attr('href'); // "../page.html#anchor"(原始文本)
3. 浏览器环境下避免自动标准化
如果希望 getAttribute
不返回标准化 URL,需确保:
- HTML 中的属性值是完整路径(如
<a href="https://example.com/page">
)。 - 如果是相对路径,浏览器一定会补全为当前域名的绝对路径。
总结对比
场景 | 方法 | 返回值 |
---|---|---|
浏览器 DOM | element.getAttribute('href') |
标准化的绝对 URL |
浏览器 DOM (原始值) | element.attributes.href.value |
HTML中原始的文本值 |
Cheerio (Node.js) | $('a').attr('href') |
HTML中原始的文本值 |
根据你的运行环境选择对应方案即可。
内容由零声教学AI助手提供,问题来源于学员提问