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

源代码: Lib/urllib/robotparser.py


此模块提供了一个单独的类 RobotFileParser,它可以回答有关某个特定用户代理能否在发布了 robots.txt 文件的网站上获取某个 URL 的问题。 有关 robots.txt 文件结构的更多细节,请参阅 RFC 9309

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

This class provides methods to read, parse and answer questions about the robots.txt file at url or a urllib.request.Request object.

在 3.16.0a0 (unreleased) 版本发生变更: url parameter can be a urllib.request.Request object.

set_url(url)

Sets the URL referring to a robots.txt file or a urllib.request.Request object.

在 3.16.0a0 (unreleased) 版本发生变更: url parameter can be a urllib.request.Request object.

read()

读取 robots.txt URL 并将其输入解析器。

parse(lines)

解析行参数。

can_fetch(useragent, url)

如果允许 useragent 按照被解析 robots.txt 文件中的规则来获取 url 则返回 True

mtime()

返回最近一次获取 robots.txt 文件的时间。 这适用于需要定期检查 robots.txt 文件更新情况的长时间运行的网页爬虫。

modified()

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

crawl_delay(useragent)

为指定的 useragentrobots.txt 返回 Crawl-delay 参数的值。 如果此参数不存在或不适用于指定的 useragent 或者此参数的 robots.txt 条目存在语法错误,则返回 None

Added in version 3.6.

request_rate(useragent)

named tuple RequestRate(requests, seconds) 的形式从 robots.txt 返回 Request-rate 参数的内容。 如果此参数不存在或不适用于指定的 useragent 或者此参数的 robots.txt 条目存在语法错误,则返回 None

Added in version 3.6.

site_maps()

list() 的形式从 robots.txt 返回 Sitemap 参数的内容。 如果此参数不存在或者此参数的 robots.txt 条目存在语法错误,则返回 None

Added in version 3.8.

下面的例子演示了 RobotFileParser 类的基本用法:

>>> import urllib.robotparser
>>> rp = urllib.robotparser.RobotFileParser()
>>> rp.set_url("http://www.pythontest.net/robots.txt")
>>> rp.read()
>>> rrate = rp.request_rate("*")
>>> rrate.requests
1
>>> rrate.seconds
1
>>> rp.crawl_delay("*")
6
>>> rp.can_fetch("*", "http://www.pythontest.net/")
True
>>> rp.can_fetch("*", "http://www.pythontest.net/no-robots-here/")
False

The following example demonstrates use of a urllib.request.Request object with additional user-agent headers populated:

>>> import urllib.robotparser
>>> import urllib.request
>>> rp = urllib.robotparser.RobotFileParser()
>>> rp.set_url(urllib.request.Request("http://www.pythontest.net/robots.txt", headers={"User-Agent": "IsraBot"}))
>>> rp.read()
>>> rp.can_fetch("*", "http://www.pythontest.net/")
True
>>> rp.can_fetch("*", "http://www.pythontest.net/no-robots-here/")
False