urllib.robotparser --- robots.txt のためのパーザ

ソースコード: Lib/urllib/robotparser.py


このモジュールでは単一のクラス、 RobotFileParser を提供します。このクラスは、特定のユーザエージェントが robots.txt ファイルを公開している Web サイトのある URL を取得可能かどうかの質問に答えます。 robots.txt ファイルの構造に関する詳細は http://www.robotstxt.org/orig.html を参照してください。

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

urlrobots.txt に対し読み込み、パーズ、応答するメソッドを提供します。

set_url(url)

robots.txt ファイルを参照するための URL を設定します。

read()

robots.txt URL を読み出し、パーザに入力します。

parse(lines)

引数 lines の内容を解釈します。

can_fetch(useragent, url)

解釈された robots.txt ファイル中に記載された規則に従ったとき、 useragenturl を取得してもよい場合には True を返します。

mtime()

robots.txt ファイルを最後に取得した時刻を返します。この値は、定期的に新たな robots.txt をチェックする必要がある、長時間動作する Web スパイダープログラムを実装する際に便利です。

modified()

robots.txt ファイルを最後に取得した時刻を現在の時刻に設定します。

crawl_delay(useragent)

Returns the value of the Crawl-delay parameter from robots.txt for the useragent in question. If there is no such parameter or it doesn't apply to the useragent specified or the robots.txt entry for this parameter has invalid syntax, return None.

バージョン 3.6 で追加.

request_rate(useragent)

Returns the contents of the Request-rate parameter from robots.txt as a named tuple RequestRate(requests, seconds). If there is no such parameter or it doesn't apply to the useragent specified or the robots.txt entry for this parameter has invalid syntax, return None.

バージョン 3.6 で追加.

site_maps()

Returns the contents of the Sitemap parameter from robots.txt in the form of a list(). If there is no such parameter or the robots.txt entry for this parameter has invalid syntax, return 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