Bun

指南HTMLRewriter

使用 Bun 中的 HTMLRewriter 从网页中提取链接

Bun 的 HTMLRewriter API 可用于高效地从 HTML 内容中提取链接。它通过链接 CSS 选择器来匹配您要处理的元素、文本和属性。这是一个从网页中提取链接的简单示例。您可以将 .transform 对象传递给 ResponseBlobstring

async function extractLinks(url: string) {
  const links = new Set<string>();
  const response = await fetch(url);

  const rewriter = new HTMLRewriter().on("a[href]", {
    element(el) {
      const href = el.getAttribute("href");
      if (href) {
        links.add(href);
      }
    },
  });

  // Wait for the response to be processed
  await rewriter.transform(response).blob();
  console.log([...links]); // ["https://bun.net.cn", "/docs", ...]
}

// Extract all links from the Bun website
await extractLinks("https://bun.net.cn");

将相对 URL 转换为绝对 URL

在抓取网站时,您通常希望将相对 URL(例如 /docs)转换为绝对 URL。以下是如何处理 URL 解析的方法。

async function extractLinksFromURL(url: string) {
  const response = await fetch(url);
  const links = new Set<string>();

  const rewriter = new HTMLRewriter().on("a[href]", {
    element(el) {
      const href = el.getAttribute("href");
      if (href) {
        // Convert relative URLs to absolute
        try {
          const absoluteURL = new URL(href, url).href;
          links.add(absoluteURL);
        } catch {
          links.add(href);
        }
      }
    },
  });

  // Wait for the response to be processed
  await rewriter.transform(response).blob();
  return [...links];
}

const websiteLinks = await extractLinksFromURL("https://example.com");

有关 Bun 的 HTML 转换的完整文档,请参阅 文档 > API > HTMLRewriter