21.10. urllib.robotparser - 用于robots.txt的解析器

源代码: Lib / urllib / robotparser.py

此模块提供了一个类RobotFileParser,用于回答有关特定用户代理是否可以在发布了robots.txt文件的网站上提取网址的问题。有关robots.txt文件结构的详情,请参阅http://www.robotstxt.org/orig.html

class urllib.robotparser.RobotFileParser(url='')

此类提供了读取,解析和回答有关网址robots.txt文件的问题的方法。

set_url(url)

设置指向robots.txt文件的网址。

read()

读取robots.txt网址,并将其提供给解析器。

parse(lines)

解析线参数。

can_fetch(useragent, url)

如果允许useragent根据解析的robots.txt中包含的规则提取url,则返回True文件。

mtime()

返回上次抓取robots.txt文件的时间。这对需要定期检查新的robots.txt文件的长时间运行的网络蜘蛛非常有用。

modified()

将上次抓取的robots.txt文件的时间设置为当前时间。

以下示例演示了RobotFileParser类的基本使用。

>>> import urllib.robotparser
>>> rp = urllib.robotparser.RobotFileParser()
>>> rp.set_url("http://www.musi-cal.com/robots.txt")
>>> rp.read()
>>> rp.can_fetch("*", "http://www.musi-cal.com/cgi-bin/search?city=San+Francisco")
False
>>> rp.can_fetch("*", "http://www.musi-cal.com/")
True