我正在尝试检测以下两个选项之一:
- 特定的机器人列表 (FacebookExternalHit|LinkedInBot|TwitterBot|Baiduspider)
- 任何不支持 Crawable Ajax 规范的机器人
我见过类似的问题(如何识别 Facebook 用户代理 https://stackoverflow.com/questions/8626812/how-to-recognize-facebook-user-agent)但没有解释如何在 Node 和 Express 中执行此操作。
我需要以如下格式执行此操作:
app.get("*", function(req, res){
if (is one of the bots) //serve snapshot
if (is not one of the bots) res.sendFile(__dirname + "/public/index.html");
});
你可以检查标题User-Agent
在请求对象中并测试不同机器人的值,
截至目前,Facebook 表示他们拥有三种类型的 User-Agent 标头值(检查Facebook 爬虫 https://developers.facebook.com/docs/sharing/webmasters/crawler),twitter 还有一个带有版本的用户代理(检查Twitter URL 抓取和缓存 https://dev.twitter.com/cards/getting-started#crawling),下面的示例应该涵盖这两个机器人。
Node
var http = require('http');
var server = http.createServer(function(req, res){
var userAgent = req.headers['user-agent'];
if (userAgent.startsWith('facebookexternalhit/1.1') ||
userAgent === 'Facebot' ||
userAgent.startsWith('Twitterbot') {
/* Do something for the bot */
}
});
server.listen(8080);
Express
var http = require('http');
var express = require('express');
var app = express();
app.get('/', function(req, res){
var userAgent = req.headers['user-agent'];
if (userAgent.startsWith('facebookexternalhit/1.1') ||
userAgent === 'Facebot' ||
userAgent.startsWith('Twitterbot') {
/* Do something for the bot */
}
});
app.listen(8080);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)