前端技术探索系列:HTML5 微数据与结构化数据指南 📊
致读者:探索数据语义化的世界 👋
前端开发者们,
今天我们将深入探讨 HTML5 微数据与结构化数据,学习如何让网页内容更易被搜索引擎理解和解析。
微数据标准实现 🚀
基础微数据标注
<!-- 产品信息示例 -->
<div itemscope itemtype="https://schema.org/Product">
<h1 itemprop="name">iPhone 13 Pro</h1>
<div itemprop="description">
新一代 iPhone,搭载 A15 仿生芯片
</div>
<div itemprop="offers" itemscope itemtype="https://schema.org/Offer">
<span itemprop="price">7999</span>
<meta itemprop="priceCurrency" content="CNY">
<link itemprop="availability" href="https://schema.org/InStock">
<meta itemprop="priceValidUntil" content="2024-12-31">
</div>
<div itemprop="aggregateRating"
itemscope
itemtype="https://schema.org/AggregateRating">
<meta itemprop="ratingValue" content="4.8">
<meta itemprop="reviewCount" content="2749">
</div>
</div>
复杂数据结构
<!-- 企业信息示例 -->
<div itemscope itemtype="https://schema.org/Organization">
<h1 itemprop="name">科技创新有限公司</h1>
<div itemprop="address" itemscope itemtype="https://schema.org/PostalAddress">
<span itemprop="streetAddress">创新路88号</span>
<span itemprop="addressLocality">深圳市</span>
<span itemprop="addressRegion">广东省</span>
<meta itemprop="postalCode" content="518000">
<meta itemprop="addressCountry" content="CN">
</div>
<div itemprop="contactPoint" itemscope itemtype="https://schema.org/ContactPoint">
<meta itemprop="contactType" content="customer service">
<span itemprop="telephone">400-888-8888</span>
<span itemprop="email">support@example.com</span>
<meta itemprop="availableLanguage" content="zh-CN">
</div>
</div>
结构化数据管理 📝
数据验证工具
class StructuredDataValidator {
constructor() {
this.schemas = new Map();
this.loadSchemas();
}
async loadSchemas() {
try {
const response = await fetch('https://schema.org/version/latest/schemaorg-current-https.jsonld');
const data = await response.json();
this.parseSchemas(data);
} catch (error) {
console.error('Schema 加载失败:', error);
}
}
parseSchemas(data) {
data['@graph'].forEach(item => {
if (item['@type'] === 'rdfs:Class') {
this.schemas.set(item['@id'], {
properties: new Set(),
required: new Set()
});
}
});
}
validateElement(element) {
const itemtype = element.getAttribute('itemtype');
if (!itemtype) return {
valid: false, error: '缺少 itemtype' };
const schemaType = this.getSchemaType(itemtype);
if (!schemaType) return {
valid: false, error: '未知的 Schema 类型' };
return this.validateProperties(element, schemaType);
}
validateProperties(element, schemaType) {
const errors = [];
const properties = element.querySelectorAll('[itemprop]');
// 检查必需属性
schemaType.required.forEach(prop =>