Robots Parser 技术文档
安装指南
通过 NPM 安装
要安装 robots-parser
,可以使用 NPM 命令:
npm install robots-parser
通过 Yarn 安装
或者使用 Yarn 命令:
yarn add robots-parser
项目使用说明
robots-parser
是一个用于解析 robots.txt
文件的工具,旨在符合 draft specification。它支持以下指令:
- User-agent
- Allow
- Disallow
- Sitemap
- Crawl-delay
- Host
- 路径中的通配符 (*) 和 EOL 匹配 ($)
基本使用示例
以下是一个基本的使用示例:
var robotsParser = require('robots-parser');
var robots = robotsParser('http://www.example.com/robots.txt', [
'User-agent: *',
'Disallow: /dir/',
'Disallow: /test.html',
'Allow: /dir/test.html',
'Allow: /test.html',
'Crawl-delay: 1',
'Sitemap: http://example.com/sitemap.xml',
'Host: example.com'
].join('\n'));
robots.isAllowed('http://www.example.com/test.html', 'Sams-Bot/1.0'); // true
robots.isAllowed('http://www.example.com/dir/test.html', 'Sams-Bot/1.0'); // true
robots.isDisallowed('http://www.example.com/dir/test2.html', 'Sams-Bot/1.0'); // true
robots.getCrawlDelay('Sams-Bot/1.0'); // 1
robots.getSitemaps(); // ['http://example.com/sitemap.xml']
robots.getPreferredHost(); // example.com
项目 API 使用文档
isAllowed(url, [ua])
返回值类型: boolean
或 undefined
该方法返回 true
如果指定的 URL 对于指定的用户代理是允许爬取的。如果 URL 对于这个 robots.txt
文件无效,则返回 undefined
。
isDisallowed(url, [ua])
返回值类型: boolean
或 undefined
该方法返回 true
如果指定的 URL 对于指定的用户代理是不允许爬取的。如果 URL 对于这个 robots.txt
文件无效,则返回 undefined
。
getMatchingLineNumber(url, [ua])
返回值类型: number
或 undefined
该方法返回匹配指定 URL 和用户代理的指令的行号。行号从 1 开始(1-based indexing)。如果没有匹配的指令,则返回 -1。如果规则是手动添加且没有行号,则返回 undefined
。
getCrawlDelay([ua])
返回值类型: number
或 undefined
该方法返回指定用户代理在请求之间应等待的秒数。如果没有为该用户代理指定爬取延迟,则返回 undefined
。
getSitemaps()
返回值类型: array
该方法返回由 sitemap:
指令指定的站点地图 URL 数组。
getPreferredHost()
返回值类型: string
或 null
该方法返回由 host:
指令指定的首选主机名,如果没有指定,则返回 null
。
项目安装方式
robots-parser
可以通过 NPM 或 Yarn 进行安装。具体安装命令如下:
通过 NPM 安装
npm install robots-parser
通过 Yarn 安装
yarn add robots-parser
通过以上步骤,您可以轻松地将 robots-parser
集成到您的项目中,并开始解析 robots.txt
文件。
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考