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.
从网页中提取链接
Bun 的 HTMLRewriter API 可用于从 HTML 内容中高效提取链接。它通过将 CSS 选择器链式组合起来,以匹配你想处理的元素、文本和属性。下面是一个从网页中提取链接的示例。你可以向 .transform 传入 Response、Blob 或 string。
extract-links.tsasync 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 解析的方法:
extract-links.tsasync 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
try {
const absoluteURL = new URL(href, url).href;
links.add(absoluteURL);
} catch {
links.add(href);
}
}
},
});
// 等待响应被处理完成
await rewriter.transform(response).blob();
return [...links];
}
const websiteLinks = await extractLinksFromURL("https://example.com");
完整的 HTML 转换文档请参见 文档 > API > HTMLRewriter 。