ZBLOG

使用linkedom解析出字符串变量中所有href action src属性的URL值,给一个示例

使用 linkedom 解析字符串中的 hrefactionsrc 属性值(完整示例)

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助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=23122

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?