我的任务是从 API 中获取页面的标题。这些数据必须可供网络爬虫抓取。这就是我到目前为止所做的。
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="description" content="Test description" />
<title>Test title</title>
<script>
document.addEventListener('DOMContentLoaded', function () {
const endPoint = 'endpoint.com'
fetch(apiEndpoint).then(function (response) {
return response.json();
})
.then(function (data) {
// change title with javascript logic
}).catch(function() {
// fallback title
})
})
</script>
</head>
<body></body>
</html>
您不需要延迟脚本的运行,因为它已经在创建标题标签之后了。
Google 和其他一些搜索引擎确实会渲染页面,并且只要不花太长时间就会看到您的更改。我发现 5 秒差不多是极限了。