Python urllib-robotparser模块
2022-08-06 本文已影响0人
大狗熊熊熊熊熊
urllib-robotparser模块可以用来确定某一url对于网络爬虫的允许爬取范围及限制
urllib-robotparse模块常用的类有
1.urllib.robotparser.RobotFileParser 《提供读取、解析url 上的 robots.txt 文件的方法,该文件为说明爬虫限制文件》
具体方法有:该方法为urllib.robotparser.RobotFileParser 类方法非urllib.robotparser类方法
set_url(url) 《设置指向rebots.txt的文件URL》
read() 《读取rebots.txt URL并将其输入解析器》
parse(lines) 《解析rebots.txt文件,传入的参数是rebots.txt文件中的某些行内容》
can_fetch(user-agent,url) 《判断user-agent是否有权限抓取url的内容》
mtime() 《返回最近一次获取rebots.txt文件的时间》
modified() 《将最近一个获取rebots.txt文件的时间设置为当前时间》
例1:
robots = urllib.robotparser.RobotFileParser()
robots.parse(urllib.request.urlopen("http://www.baidu.com/robots.txt").read().decode("utf-8").split("\n"))
print(robots.can_fetch("Baiduspider","http://www.baidu.com"))
print(robots.can_fetch("Baiduspider","http://www.baidu.com/homepage/"))
print(robots.can_fetch("Googlebot","http://www.baidu.com/homepage/"))
print(robots.can_fetch("Baiduspider","http://www.baidu.com/board/"))
输出:TRUE TRUE FALSE TRUE
例2:
robots = urllib.robotparser.RobotFileParser()
robots.set_url("https://www.baidu.com/robots.txt")
robots.read()
print(robots.can_fetch("Baiduspider","https://www.baidu.com"))
print(robots.can_fetch("Baiduspider","https://www.baidu.com/homepage/"))
print(robots.can_fetch("Googlebot","https://www.baidu.com/homepage/"))
print(robots.can_fetch("Baiduspider","https://www.baidu.com/board/"))
输出:TRUE TRUE FALSE TRUE
例3:
robots = urllib.robotparser.RobotFileParser("https://www.baidu.com/robots.txt")
robots.read()
print(robots.can_fetch("Baiduspider","https://www.baidu.com"))
print(robots.can_fetch("Baiduspider","https://www.baidu.com/homepage/"))
print(robots.can_fetch("Googlebot","https://www.baidu.com/homepage/"))
print(robots.can_fetch("Baiduspider","https://www.baidu.com/board/"))
输出:TRUE TRUE FALSE TRUE