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.nodejs.com.tw", "/docs", ...]
}

// Extract all links from the Bun website
await extractLinks("https://bun.nodejs.com.tw");

將相對 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