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

// Extract all links from the Bun website
await extractLinks("https://bun.dev.org.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");

請參閱文件 > API > HTMLRewriter,以取得關於使用 Bun 進行 HTML 轉換的完整文件。