← 中文资源

简体中文版本

从 HTML 中抽取白名单内的链接

从 HTML 片段中抽取锚点 href 与可见文本,只保留白名单主机,并报告跳过了多少链接。

阅读英文原文

任务

匹配所有 标签,剥离标签得到可见文本,解析 href 主机并与白名单比对,其余计入 skipped。

契约

  • 输入:JSON 对象:{ html: string, allowedHosts: string[] }
  • 输出:JSON 对象:{ links: [{ href, text }], skipped: number }

样例

  1. 输入 {"html":"<a href=\"https://docs.example.com/start\">Start</a><a href=\"https://ads.other.com/x\">Ad</a>","allowedHosts":["docs.example.com"]} -> 期望 {"links":[{"href":"https://docs.example.com/start","text":"Start"}],"skipped":1}。站外链接被计为跳过,而不是被悄悄忽略。
  2. 输入 {"html":"<a href=\"https://docs.example.com/a\"><b>Bold</b> label</a>","allowedHosts":["docs.example.com"]} -> 期望 {"links":[{"href":"https://docs.example.com/a","text":"Bold label"}],"skipped":0}。嵌套标记会从可见文本里被剥除。

参考实现

function solve({ html, allowedHosts }) {
      const anchors = [...String(html).matchAll(/<a\s+[^>]*href="([^"]+)"[^>]*>([\s\S]*?)<\/a>/gi)].map((match) => ({
        href: match[1],
        text: match[2].replace(/<[^>]+>/g, '').trim(),
      }));
      const kept = anchors.filter((anchor) => {
        const host = anchor.href.replace(/^https?:\/\//, '').split('/')[0];
        return allowedHosts.includes(host);
      });
      return { links: kept, skipped: anchors.length - kept.length };
    }

为什么有效

跟随所有链接的爬虫会跑到站外并重复劳动。主机白名单是让抓取保持聚焦的最简边界。

标签要从文本里剥掉,但 href 必须原样保留;改写 href 会破坏规范化追踪。