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
Python urllib-robotparser模块
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- 使用urllib和urllib2模块。 简单的下拉一个网页 urlopen一般接受三个参数,url、date、ti...
- urllib urllib是一个收集了多个涉及 URL 的模块的包: urllib.request[https:/...