On this page
13.3. robotparser — robots.txt 的解析器
Note
robotparser模块在 Python 3 中已重命名为urllib.robotparser
。在将源转换为 Python 3 时,2to3工具将自动适应导入。
该模块提供一个单一类RobotFileParser,该类回答有关特定用户代理是否可以在发布robots.txt
文件的网站上获取 URL 的问题。有关robots.txt
文件结构的更多详细信息,请参见http://www.robotstxt.org/orig.html。
-
- class *
robotparser.
RobotFileParser
(* url =''*)
- 此类提供了用于读取,解析和回答有关位于 url *的
robots.txt
文件的问题的方法。
- class *
set_url
(* url *)- 设置引用
robots.txt
文件的 URL。
- 设置引用
read
( )- 读取
robots.txt
URL 并将其提供给解析器。
- 读取
parse
(行)- 解析 lines 参数。
can_fetch
(* useragent , url *)- 如果允许* useragent 根据解析的
robots.txt
文件中包含的规则获取 url *,则返回True
。
- 如果允许* useragent 根据解析的
mtime
( )- 返回上一次获取
robots.txt
文件的时间。这对于需要定期检查新的robots.txt
文件的长期运行的网络蜘蛛非常有用。
- 返回上一次获取
modified
( )- 将
robots.txt
文件的最后获取时间设置为当前时间。
- 将
以下示例演示了 RobotFileParser 类的基本用法。
>>> import robotparser
>>> rp = 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