我正在使用Google's Structured Data Testing Tool来验证我的架构。这个页面就是一个很好的例子:https://www.bigmazda.com/new-mazda-cx-9-longwood-fl.html。
我在上面的网站上使用Google跟踪代码管理器。在GTM中,我创建了一个自定义HTML标记并放置了以下代码:
<script>
(function(){
var schemaData = {
"@context": "http://schema.org/",
"@type": "Product",
"name": "{{schemaName}}",
"image": "{{schemaImage}}",
"description": "{{schemaDescription}}",
"brand": {
"@type": "Thing",
"name": "{{schemaBrandName}}"
},
"aggregateRating": {
"@type": "AggregateRating",
"ratingValue": "{{schemaRatingValue}}",
"reviewCount": "{{schemaReviewCount}}",
},
"offers": {
"@type": "Offer",
"priceCurrency": "USD",
"price": "{{schemaPrice}}",
"itemCondition": "http://schema.org/NewCondition",
"availability": "http://schema.org/InStock",
"seller": {
"@type": "Organization",
"name": "{{schemaSellerName}}"
}
}
}
var script = document.createElement('script');
script.type = "application/ld+json";
script.innerHTML = JSON.stringify(schemaData);
document.getElementsByTagName('head')[0].appendChild(script);
})(document);
</script>
同样在自定义HTML中我启用了“支持document.write”。
上面的代码有八个GTM变量,但以下四个给我带来了麻烦:
{{schemaRatingValue}}
{{schemaReviewCount}}
{{schemaPrice}}
{{schemaName}}
注意:我正在获得其他四个变量,他们正在使用结构化数据测试工具进行验证。
对于上面的每个项目,这就是我在GTM中使用Custom JavaScript变量来获取每个值的方法:
function(){
var schemaRatingValue = Number(document.getElementsByClassName('model-review')[0].innerText.split(" ")[1]);
return schemaRatingValue;
}
function(){
var review = document.getElementsByClassName('model-review')[0].innerText.split(" ")[2].replace(/[{()}]/g, '');
var schemaReviewCount = Number(review);
return schemaReviewCount;
}
function(){
var schemaPrice = Number(document.getElementsByClassName('mrPriceRange')[0].innerText.split(" ")[0].replace(/[$,]+/g, ''));
return schemaPrice;
}
function() {
var schemaName = document.getElementsByTagName('h1')[0].getElementsByTagName('span')[0].innerText;
return schemaName;
}
使用GTM的预览模式时,我会按预期看到架构:
但是,使用结构化数据测试工具时,我看到:
注意:使用控制台I验证{{schemaRatingValue}}
,{{schemaReviewCount}}
和{{schemaPrice}}
是整数类型。当谈到{{schemaName}}
时,我不确定为什么不显示,因为它是一个简单的字符串。
注意:{{schemaPrice}}
不显示错误但它显示0,它应显示33335,基于Inspector屏幕截图。
上面我的问题的解决方案是我遍历DOM的方法。
获取以下值:
{{schemaRatingValue}}
{{schemaReviewCount}}
{{schemaPrice}}
{{schemaName}}
使用XPath证明了答案。此代码用于设置解析XPath:
function getElementByXpath(path) {
return document.evaluate(path, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
}
然后使用此代码来定位DOM所需的特定对象:
var schemaPriceModelXpath = getElementByXpath("//*[@id=\"cBlock1\"]/div[2]/div[2]/div/div[1]/div[1]/h4/span[1]");
为了获得整数,我使用以下方法转换了Object:
var schemaPriceModelXpathNumber = schemaPriceModelXpathText.replace(/[$,]+/g, '');
var schemaPriceModel = parseFloat(schemaPriceModelXpathNumberPrice);
return schemaPriceModel;
为了获取字符串,我使用以下方法转换了Object:
var schemaNameModelXpathText = schemaNameModelXpath.textContent
return schemaNameModelXpathText;
使用上面的方法,我能够获得上面列出的四个变量的值。
最后一步是使用Google's Structured Data Testing Tool验证此方法
这是一个截屏:Schema Validation using Google Structured Data Testing Tool