執行環境套件管理器打包器測試執行器程式碼檢查格式化指南參考部落格意見回饋

使用 HTMLRewriter 提取網頁中的連結

從網頁中提取連結

Bun 的 HTMLRewriter API 可從 HTML 中提取連結。通過 CSS 選擇器鏈匹配要處理的元素、文本和屬性。然後將 Response、ArrayBuffer 或 string 傳遞給 .transform。

extract-links.ts
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);
      }
    },
  });

  // 等待響應被處理完成
  await rewriter.transform(response).blob();
  console.log([...links]); // ["https://bun.sh", "/docs", ...]
}

// 從 Bun 網站提取所有連結
await extractLinks("https://bun.sh");

將相對 URL 轉換為絕對 URL

抓取網站時,你通常需要將相對 URL(例如 /docs)轉換為絕對 URL:

extract-links.ts
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) {
        // 將相對 URL 轉換為絕對 URL // [!code ++]
        try { // [!code ++]
          const absoluteURL = new URL(href, url).href; // [!code ++]
          links.add(absoluteURL);
        } catch { // [!code ++]
          links.add(href); // [!code ++]
        } // [!code ++]
      }
    },
  });

  // 等待響應被處理完成
  await rewriter.transform(response).blob();
  return [...links];
}

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

請參閱 HTMLRewriter。