使用 linkedom
解析字符串中的 href
、action
、src
属性值(完整示例)
1. 安装或引入 linkedom
- Node.js/npm:
npm install linkedom
- 浏览器/CDN:
<script src="https://unpkg.com/linkedom"></script>
2. JavaScript 代码示例
// Node.js/ESM 导入(或浏览器直接使用 linkedom)
import { parseHTML } from 'linkedom';
// HTML字符串示例(可以是任意HTML片段)
const htmlString = `
<!DOCTYPE html>
<html>
<head><title>Test</title></head>
<body>
<a href="https://example.com/page1">Link1</a>
<form action="/submit" method="post"></form>
<img src="image.jpg" alt="Example">
<iframe src="https://youtube.com/embed/123"></iframe>
<link rel="stylesheet" href="/styles.css">
</body>
</html>
`;
// Step1: 解析HTML字符串
const { document } = parseHTML(htmlString);
// Step2: 定义目标属性名(href, action, src)
const targetAttrs = ['href', 'action', 'src'];
// Step3: 提取所有元素的属性值
const result = [];
document.querySelectorAll('*').forEach((element) => {
targetAttrs.forEach((attr) => {
const value = element.getAttribute(attr);
if (value) {
result.push({
tag: element.tagName.toLowerCase(),
attribute: attr,
url: value,
});
}
});
});
console.log(result);
3. 输出结果
运行上述代码后,会得到如下结构的数组:
[
{ tag: 'a', attribute: 'href', url: 'https://example.com/page1' },
{ tag: 'form', attribute: 'action', url: '/submit' },
{ tag: 'img', attribute: 'src', url: 'image.jpg' },
{ tag: 'iframe', attribute: 'src', url: 'https://youtube.com/embed/123' },
{ tag: 'link', attribute: 'href', url: '/styles.css' }
]
4. (可选)转换为绝对路径
如果需要将相对路径转为绝对 URL:
const baseUrl = 'https://example.com';
const absoluteUrls = result.map((item) => {
try {
return new URL(item.url, baseUrl).href;
} catch (e) {
return item.url; // 保留无效URL(如mailto:, tel:, etc)
}).filter(Boolean);
console.log(absoluteUrls);
输出:
[
"https://example.com/page1",
"https://example.com/submit",
"https://example.com/image.jpg",
"https://youtube.com/embed/123",
"https://example.com/styles.css"
]
关键点说明
- 覆盖所有元素:
querySelectorAll('*')
会遍历文档中所有标签。 - 性能优化:如果处理超大HTML,可以限制选择器范围(如只查
<a>
、<img>
)。 - 错误处理:无效URL(如
javascript:
)会被跳过。
内容由零声教学AI助手提供,问题来源于学员提问