robots.txt文件规定了爬虫在爬取该网站时有哪些约束。
robots.txt示例
下面给出一个robots.txt示例:
禁止用户代理为BadCrawler的爬虫爬取该网站
#section 1
User-agent: BadCrawler
Disallow: /
无论哪种用户代理,都应该在两次下载请求之间有5秒的时延;/trap链接是禁止链接,如果访问了这个链接,服务器就会封禁你的IP一分钟或者永久封禁
# section 2
User-agent: *
Crawl-delay: 5
Disallow: /trap
# section 3
Sitemap: http://example.com/sitemap.xml
解析robots.txt
>>>import robotparser
>>>rp = robotparser.RobotFileParser()
>>>rp.set_url('http://example.com/robots.txt')
>>>rp.read()
>>>url = 'http://example.com'
>>>user_agent = 'BadCrawler'
>>>rp.can_fetch(user_agent, url)#是否允许指定的用户代理访问网页
False
>>>user_agent = 'GoodCrawler'
>>>rp.can_fetch(user_agent, url)
>True