urllib.robotparser — robots.txt 解析器

源代码: Lib/urllib/robotparser.py


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

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

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

set_url(url)

设置指向 robots.txt 文件的 URL。

read()

读取 robots.txt URL 并将其提供给解析器。

parse(lines)

解析行参数。

can_fetch(useragent, url)

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

mtime()

返回上次获取 robots.txt 文件的时间。这对于需要定期检查新的 robots.txt 文件的长时间运行的网页蜘蛛很有用。

modified()

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

crawl_delay(useragent)

返回 robots.txt 中针对给定 useragentCrawl-delay 参数的值。如果不存在此类参数,或者它不适用于指定 useragent,或者此参数的 robots.txt 条目语法无效,则返回 None

在 3.6 版本加入。

request_rate(useragent)

返回 robots.txtRequest-rate 参数的内容,形式为 具名元组 RequestRate(requests, seconds)。如果不存在此类参数,或者它不适用于指定 useragent,或者此参数的 robots.txt 条目语法无效,则返回 None

在 3.6 版本加入。

site_maps()

list() 的形式返回 robots.txtSitemap 参数的内容。如果不存在此类参数,或者此参数的 robots.txt 条目语法无效,则返回 None

在 3.8 版本加入。

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

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