使用robotparser模块来解析robots.txt文件,该模块提供了一个RobotFileParser,它可以根据网站的robots.txt文件判断一个爬虫是否有权限爬取这个网页。
语法:
urllib.robotparser.RobotFileParser(url='')
https://www.baidu.com/robots.txt的内容如下(截取部分内容):
User-agent: Baiduspider # 百度爬虫
Disallow: /baidu # 不允许爬取/baidu下的内容
Disallow: /s? # 不允许爬取/s?下的内容
Disallow: /ulink? # 不允许爬取/ulink?下的内容
Disallow: /link? # 不允许爬取/link?下的内容
Disallow: /home/news/data/ # 不允许爬取/home/news/data/下的内容
Disallow: /bh # 不允许爬取/bh下的内容
User-agent: Googlebot # 谷歌爬虫
Disallow: /baidu # 不允许爬取/baidu下的内容
Disallow: /s? # 不允许爬取/s?下的内容
Disallow: /shifen/ # 不允许爬取/shifen/下的内容
Disallow: /homepage/ # 不允许爬取/homepage/下的内容
Disallow: /cpro # 不允许爬取/cpro下的内容
Disallow: /ulink? # 不允许爬取/ulink?下的内容
Disallow: /link? # 不允许爬取/link?下的内容
Disallow: /home/news/data/ # 不允许爬取/home/news/data/下的内容
Disallow: /bh # 不允许爬取/bh下的内容
User-agent: * # 其它爬虫,指robots.txt文件协议中没有指出的其它爬虫
Disallow: / # 不允许爬取网站的所有目录及内容
1、方法1:在声明对象时,直接传入robots.txt文件的链接
# Python版本:3.6
# -*- coding:utf-8 -*-
from urllib.robotparser import RobotFileParser
# 在声明对象时,直接传入robots.txt文件的链接
rp = RobotFileParser('https://www.baidu.com/robots.txt')
# 不能缺失,一定要调用此方法,否则can_fetch方法中全都判断为False,该方法用来解析robots.txt文件并进行分析
rp.read()
# 允许百度爬虫访问 域名的根目录
print(rp.can_fetch('Baiduspider','https://www.baidu.com')) # True
# 允许百度爬虫访问 目录/homepage/
print(rp.can_fetch('Baiduspider','https://www.baidu.com/homepage/')) # True
# 禁止谷歌爬虫访问 目录/homepage/