-
声明:

只需要在使用该类时传入robot.txt的url连接即可
-
set_url ()方法:用来设置robot.txt文件的连接

-
read()方法:读取robot.txt文件进行分析

-
parse()方法:用于解析robot.txt文件

-
can_fetch()方法:有两个参数,第一个是user-Agent,第二个是要抓取的URL,返回的结果是 True 或 False 。表示user-Agent指示的搜索引擎是否可以抓取这个URL。

-
mtime()方法:返回上次抓取和分析robots.txt的时间,这对于长时间分析和抓取robots.txt文件的搜索爬虫很有必要,我们要定期检查来抓取最新的robots.txt
-
modified()方法:他同样对长时间抓取和分析的搜索爬虫很有必要,可以将当前时间设置为上次抓取和分析robots.txt文件的时间。
-
实例
from urllib import robotparser
rp = robotparser.RobotFileParser()
rp.set_url('https://www.baidu.com/robots.txt')
rp.read()
print(rp.can_fetch('Baiduspider','https://www.baidu.com'))
print(rp.can_fetch('Baiduspider','https://www.baidu.com/homepage/'))
print(rp.can_fetch('Googlebot','https://www.baidu.com/homepage/'))
运行结果 :

打开百度的robots.txt

可以看到其对Baiduspider没有限制