
# section 1 User-agent: BadCrawler Disallow: / # section 2 User-agent: * Disallow: /trap Crawl-delay: 5 # section 3 Sitemap: http://example.python-scraping.com/sitemap.xml
这个 robots.txt 文件中说:对于BadCrawler 这样的代理用户是禁止浏览本站点的。
我们现在使用这个 Python 自带的 robotparser 模块测试一下:
from urllib import robotparser
# 将创建RobotFileParser对象封装成函数,传入文件的链接,返回解析器对象
def get_robots_parser(robots_url):
rp = robotparser.RobotFileParser()
rp.set_url(robots_url)
rp.read()
print(rp)
url = 'http://example.python-scraping.com'
user_agent = 'BadCrawler'
print('BadCrawler:',rp.can_fetch(user_agent, url))
user_agent = 'GoodCrawler'
print('GoodCrawler:',rp.can_fetch(user_agent, url))
return rp
get_robots_parser('http://example.python-scraping.com/robots.txt')
User-agent: BadCrawler
Disallow: /User-agent: *
Crawl-delay: 5
Disallow: /trap
BadCrawler: False
GoodCrawler: True
上面测试说明,如果将爬虫程序的 代理用户 设置为: BadCrawler
由于你访问的目标站点已经警告你了:“我们禁止用户代理为BadCrawler 的用户访问本站点里面的所有网站”。所以,我们用 robotparser 模块创建的对象,通过rp.can_fetch(user_agent, url)函数返回 :False 。
在can_fetch() 函数前面的一堆都是初始化,can_fetch() 函数是在程序里面使用,它的功能:确定指定的用户代理是否允许访问网页。