提取社交分享图片和开放图谱标签
Bun 的 HTMLRewriter API 可以高效地从 HTML 内容中提取社交分享图片和开放图谱(Open Graph)元数据。这对于构建链接预览功能、社交媒体卡片或网页爬虫特别有用。我们可以使用 HTMLRewriter 来匹配 CSS 选择器,从而处理我们想要操作的 HTML 元素、文本和属性。Copy
interface SocialMetadata {
title?: string;
description?: string;
image?: string;
url?: string;
siteName?: string;
type?: string;
}
async function extractSocialMetadata(url: string): Promise<SocialMetadata> {
const metadata: SocialMetadata = {};
const response = await fetch(url);
const rewriter = new HTMLRewriter()
// 提取开放图谱(Open Graph)meta 标签
.on('meta[property^="og:"]', {
element(el) {
const property = el.getAttribute("property");
const content = el.getAttribute("content");
if (property && content) {
// 将 "og:image" 转换为 "image" 等等
const key = property.replace("og:", "") as keyof SocialMetadata;
metadata[key] = content;
}
},
})
// 作为备用,提取 Twitter Card meta 标签
.on('meta[name^="twitter:"]', {
element(el) {
const name = el.getAttribute("name");
const content = el.getAttribute("content");
if (name && content) {
const key = name.replace("twitter:", "") as keyof SocialMetadata;
// 仅当没有 OG 数据时使用 Twitter Card 数据
if (!metadata[key]) {
metadata[key] = content;
}
}
},
})
// 备用,提取普通 meta 标签
.on('meta[name="description"]', {
element(el) {
const content = el.getAttribute("content");
if (content && !metadata.description) {
metadata.description = content;
}
},
})
// 备用,提取标题标签
.on("title", {
text(text) {
if (!metadata.title) {
metadata.title = text.text;
}
},
});
// 处理响应内容
await rewriter.transform(response).blob();
// 将相对图片 URL 转换为绝对 URL
if (metadata.image && !metadata.image.startsWith("http")) {
try {
metadata.image = new URL(metadata.image, url).href;
} catch {
// 如果解析失败,则保留原始 URL
}
}
return metadata;
}
Copy
// 示例用法
const metadata = await extractSocialMetadata("https://bun.com");
console.log(metadata);
// {
// title: "Bun — A fast all-in-one JavaScript runtime",
// description: "Bundle, transpile, install and run JavaScript & TypeScript projects — all in Bun. Bun is a fast all-in-one JavaScript runtime & toolkit designed for speed, complete with a bundler, test runner, and Node.js-compatible package manager.",
// image: "https://bun.com/share.jpg",
// type: "website",
// ...
// }