请问谁有识别搜索引擎的Nodejs包
请问谁有识别搜索引擎的Nodejs包
请问谁有识别搜索引擎的包,不想自己写,不完整。
4 回复
标题:请问谁有识别搜索引擎的Node.js包?
内容:
在开发过程中,我们有时需要识别访问网站的是不是搜索引擎爬虫。幸运的是,Node.js 社区提供了许多现成的库来帮助我们完成这项任务。一个常用的库是 user-agent-parser
,它可以解析用户代理字符串(User-Agent),从而帮助我们识别访问者是否为搜索引擎。
示例代码
首先,你需要安装 user-agent-parser
这个库。你可以使用 npm 来安装它:
npm install useragent
然后,你可以使用以下代码来检查访问者是否为搜索引擎:
const useragent = require('useragent');
function isSearchEngine(userAgentString) {
const agent = useragent.parse(userAgentString);
const botPatterns = [
'Googlebot', // Google
'Bingbot', // Bing
'Slurp', // Yahoo
'DuckDuckBot', // DuckDuckGo
'Baiduspider', // Baidu
'YandexBot', // Yandex
'Sogou', // Sogou
'Exabot', // Exalead
'Facebot', // Facebook
'ia_archiver', // Alexa
'MJ12bot', // Majestic
'Ezooms', // Ezooms
'CCBot', // CommonCrawl
'AhrefsBot', // Ahrefs
'rogerbot', // Moz
'DotBot', // Dot SEO
'SemrushBot' // Semrush
];
return botPatterns.some(pattern => agent.family.includes(pattern));
}
// 使用示例
const userAgentString = 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)';
console.log(isSearchEngine(userAgentString)); // 输出: true
const userAgentString2 = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36';
console.log(isSearchEngine(userAgentString2)); // 输出: false
解释
- useragent: 这是一个流行的库,用于解析用户代理字符串。
- isSearchEngine 函数: 接收一个用户代理字符串,并通过检查该字符串是否包含已知的搜索引擎标识符来判断访问者是否为搜索引擎。
- botPatterns 数组: 包含了常见的搜索引擎的用户代理字符串标识符。
- some 方法: 用于检查数组中的任意元素是否满足给定条件。在这个例子中,它检查用户代理字符串是否包含任何一个搜索引擎的标识符。
通过这种方式,我们可以轻松地识别访问者是否为搜索引擎,而无需自己编写复杂的逻辑。
@.@自己把自己挖的坑填一下。 ua-parser-js uas-parser
希望有用得着的。
和楼主同样想法,自己收集了个常见搜索引擎的ua正则表达式列表 https://github.com/andyhu/search-engine-bot-list 欢迎大家一起维护更新