robots也称为爬虫协议和机器人协议。全名为“网络爬虫排除标准”,用来告诉爬虫和搜索引擎那些页面可以爬取,那些不可以爬取。
利用urllib中的robotparser模块能够对协议进行分析
当爬虫爬取网站时会在根目录和网站的入口文件下查找robots.txt文件。
robots.txt的内容一般如下
User-agent:* #描述爬虫名称
Disallow:/ #不允许抓取的目录
Allow:/public/ #允许抓取的目录
#意思是对所有爬虫只允许爬取public目录的功能
1.robotparser
该模块提供了一个RotbotfileParser的类,用起来非常简单,只要向构造方法中传入url即可。也可不传入url,用set_url方法来设置路径
1.1set_url
设置robots文件的链接
#!usr/bin/env python
#-*- coding:utf-8 -*-
from urllib.robotparser import RobotFileParser
RobotFileParser().set_url(url=' ')
2.read()
读取robots文件并进行分析
3.parse
用来解析robots文件,传入的是robots文件的某行内容,会按照robots的规则来解析
4.can_fetch()
传入两个参数:User-agent和要抓取的url,返回的是true或false
5.mtime()
返回上次抓取的时间
6.modified
将当前时间设置为上次抓取和分析robots的时间。
2.robots综合运用
#!usr/bin/env python
#-*- coding:utf-8 -*-
from urllib.robotparser import RobotFileParser
rfp=RobotFileParser()
rfp.set_url(url='http://www.csdn.net/robots.txt')
rfp.read()
print(rfp.can_fetch('*','https://www.csdn.net/article'))