urllib.robotparser --- robots.txt 用のパーサー

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


このモジュールは、robots.txt ファイルを公開しているウェブサイトから、特定のユーザーエージェントが URL を取得してよいかどうかを判定するクラス RobotFileParser を提供します。 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 で変更: 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 で変更: url parameter can be a urllib.request.Request object.

read()

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

parse(lines)

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

can_fetch(useragent, url)

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

mtime()

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

modified()

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

crawl_delay(useragent)

robots.txt から、指定した useragent に対応する Crawl-delay パラメータの値を返します。 パラメータがない、指定した useragent に適用されない、または robots.txt の該当エントリーの構文が無効な場合は、None を返します。

Added in version 3.6.

request_rate(useragent)

robots.txt の Request-rate パラメータの内容を、名前付きタプル RequestRate(requests, seconds) として返します。 パラメータがない、指定した useragent に適用されない、または robots.txt の該当エントリーの構文が無効な場合は、None を返します。

Added in version 3.6.

site_maps()

robots.txt の Sitemap パラメーターの内容を list() の形式で返します。そのようなパラメーターが存在しないか、 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