Extrair links de uma página web
A API HTMLRewriter do Bun pode ser usada para extrair links de conteúdo HTML de forma eficiente. Funciona encadeando seletores CSS para corresponder aos elementos, texto e atributos que você deseja processar. Este é um exemplo simples de como extrair links de uma página web. Você pode passar para .transform uma Response, Blob ou string.
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);
}
},
});
// Aguarde a resposta ser processada
await rewriter.transform(response).blob();
console.log([...links]); // ["https://bun.com", "/docs", ...]
}
// Extrair todos os links do site Bun
await extractLinks("https://bun.com");Converter URLs relativas para absolutas
Ao fazer scraping de sites, você frequentemente deseja converter URLs relativas (como /docs) para URLs absolutas. Veja como lidar com resolução de URL:
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) {
// Converter URLs relativas para absolutas
try {
const absoluteURL = new URL(href, url).href;
links.add(absoluteURL);
} catch {
links.add(href);
}
}
},
});
// Aguarde a resposta ser processada
await rewriter.transform(response).blob();
return [...links];
}
const websiteLinks = await extractLinksFromURL("https://example.com");Veja Docs > API > HTMLRewriter para documentação completa sobre transformação HTML com Bun.