12.6.1 爬虫的规矩——爬虫伦理:robots.txt 与网站条款
一句话破题
robots.txt 是网站对爬虫的"门禁规则"——虽然不是强制执行的法律,但遵守它是爬虫开发者的基本礼仪。
robots.txt 解读
# https://example.com/robots.txt
User-agent: * # 适用于所有爬虫
Disallow: /admin/ # 禁止爬取 /admin/ 路径
Disallow: /private/ # 禁止爬取 /private/ 路径
Allow: /public/ # 允许爬取 /public/ 路径
Crawl-delay: 10 # 建议每次请求间隔 10 秒
User-agent: Googlebot # 专门针对 Google 爬虫的规则
Allow: / # 允许爬取所有内容
Sitemap: https://example.com/sitemap.xml # 站点地图位置解析 robots.txt
typescript
interface RobotRule {
userAgent: string;
allow: string[];
disallow: string[];
crawlDelay?: number;
}
async function parseRobotsTxt(domain: string): Promise<RobotRule[]> {
const response = await fetch(`${domain}/robots.txt`);
const text = await response.text();
const rules: RobotRule[] = [];
let currentRule: RobotRule | null = null;
for (const line of text.split('\n')) {
const trimmed = line.trim();
if (trimmed.startsWith('#') || !trimmed) continue;
const [key, ...valueParts] = trimmed.split(':');
const value = valueParts.join(':').trim();
switch (key.toLowerCase()) {
case 'user-agent':
if (currentRule) rules.push(currentRule);
currentRule = { userAgent: value, allow: [], disallow: [] };
break;
case 'allow':
currentRule?.allow.push(value);
break;
case 'disallow':
currentRule?.disallow.push(value);
break;
case 'crawl-delay':
if (currentRule) currentRule.crawlDelay = parseInt(value);
break;
}
}
if (currentRule) rules.push(currentRule);
return rules;
}
function isPathAllowed(rules: RobotRule[], path: string, userAgent = '*'): boolean {
const rule = rules.find(r => r.userAgent === userAgent) || rules.find(r => r.userAgent === '*');
if (!rule) return true;
for (const disallowed of rule.disallow) {
if (path.startsWith(disallowed)) return false;
}
return true;
}服务条款注意事项
除了 robots.txt,还需要关注网站的服务条款(ToS):
| 条款类型 | 示例 | 风险等级 |
|---|---|---|
| 禁止自动化访问 | "不得使用自动化工具访问本网站" | 高 |
| 数据使用限制 | "不得将数据用于商业用途" | 高 |
| 频率限制 | "每分钟不得超过 100 次请求" | 中 |
| 版权声明 | "所有内容版权归本网站所有" | 高 |
合法爬取的原则
- 遵守 robots.txt:这是最基本的礼仪
- 阅读服务条款:了解网站的具体限制
- 控制请求频率:不要给网站带来负担
- 标识你的爬虫:设置合理的 User-Agent
- 尊重版权:不要复制受版权保护的内容
AI 协作指南
- 核心意图:让 AI 帮你理解和遵守爬虫规则。
- 需求定义公式:
"请帮我解析这个 robots.txt 文件,并判断我是否可以爬取 /products 路径。" - 关键术语:
robots.txt、User-Agent、Disallow、Crawl-delay
避坑指南
- robots.txt 是君子协定:技术上可以忽略,但会带来法律和道德风险。
- 不同 User-Agent 规则不同:确认你的爬虫身份适用哪条规则。
- 404 不代表允许:robots.txt 不存在不代表可以随意爬取。
