> ## Documentation Index
> Fetch the complete documentation index at: https://bun.zhcndoc.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 使用 HTMLRewriter 提取网页中的链接

## 从网页中提取链接

Bun 的 [HTMLRewriter](/runtime/html-rewriter) API 可用于从 HTML 内容中高效提取链接。它通过将 CSS 选择器链式组合起来，以匹配你想处理的元素、文本和属性。下面是一个从网页中提取链接的示例。你可以向 `.transform` 传入 `Response`、`Blob` 或 `string`。

```ts extract-links.ts icon="https://mintcdn.com/bun-zhcndoc/cnUTwgMuf4cCrwC-/icons/typescript.svg?fit=max&auto=format&n=cnUTwgMuf4cCrwC-&q=85&s=e7767043c9e885c34f2d6c8fe2a95217" theme={"theme":{"light":"github-light","dark":"dracula"}}
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.com", "/docs", ...]
}

// 从 Bun 网站提取所有链接
await extractLinks("https://bun.com");
```

***

## 将相对 URL 转换为绝对 URL

在爬取网站时，你通常希望将相对 URL（如 `/docs`）转换为绝对 URL。以下是处理 URL 解析的方法：

```ts extract-links.ts icon="https://mintcdn.com/bun-zhcndoc/cnUTwgMuf4cCrwC-/icons/typescript.svg?fit=max&auto=format&n=cnUTwgMuf4cCrwC-&q=85&s=e7767043c9e885c34f2d6c8fe2a95217" theme={"theme":{"light":"github-light","dark":"dracula"}}
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");
```

***

完整的 HTML 转换文档请参见 [文档 > API > HTMLRewriter](/runtime/html-rewriter) 。
