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)¶

如果�许 useragent 按照被解� robots.txt 文件中的规则�获� url 则返回 True。

mtime()¶

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

modified()¶

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

crawl_delay(useragent)¶

为指定的 useragent 从 robots.txt 返回 Crawl-delay 形�。 如果此形��存在或�适用于指定的 useragent 或者此形�的 robots.txt �目存在语法错误,则返回 None。

在 3.6 版本加入.

request_rate(useragent)¶

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

在 3.6 版本加入.

site_maps()¶

以 list() 的形�从 robots.txt 返回 Sitemap 形�的内容。 如果此形��存在或者此形�的 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