# Extract links from a webpage using HTMLRewriter (/docs/guides/html-rewriter/extract-links)

<!-- agent-signals: reading_time_min: 1 · est_tokens: 486 · updated: 2026-07-28 -->
Related: [Extract social share images and Open Graph tags](/docs/guides/html-rewriter/extract-social-meta.md), [import, require, and test Svelte components with bun test](/docs/guides/test/svelte-test.md)

## Extract links from a webpage [#extract-links-from-a-webpage]

Bun's [HTMLRewriter](/runtime/html-rewriter) API extracts links from HTML. Chain CSS selectors to match the elements, text, and attributes you want to process, then pass `.transform` a `Response`, `ArrayBuffer`, or `string`.

```ts extract-links.ts icon="/icons/typescript.svg"
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.com", "/docs", ...]
}

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

***

## Convert relative URLs to absolute [#convert-relative-urls-to-absolute]

When scraping websites, you often want to convert relative URLs (like `/docs`) to absolute URLs:

{/* prettier-ignore */}

```ts extract-links.ts icon="/icons/typescript.svg"
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 // [!code ++]
        try { // [!code ++]
          const absoluteURL = new URL(href, url).href; // [!code ++]
          links.add(absoluteURL);
        } catch { // [!code ++]
          links.add(href); // [!code ++]
        } // [!code ++]
      }
    },
  });

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

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

***

See [`HTMLRewriter`](/runtime/html-rewriter).
