Python urllib.request モジュール

urllib.request モジュールを使うと、Python 標準ライブラリで URL からデータを取得できます。

from urllib import request

多くのプロジェクトでは、Requests のようなサードパーティライブラリのほうが便利です。標準ライブラリだけで済ませたいときに urllib.request を使います。

URL を開く

urlopen はレスポンスオブジェクトを返します。

from urllib import request

response = request.urlopen('data:text/plain,Hello%20Python')
print(response.headers.get_content_type())
text/plain

レスポンスデータを読む

レスポンス本文は bytes として返されます。

from urllib import request

response = request.urlopen('data:text/plain,Hello%20Python')
content = response.read()
print(type(content).__name__)
print(content.decode('utf-8'))
bytes
Hello Python

タイムアウトを追加する

実際のネットワーク URL を開くときは、プログラムが永遠に待たないようにタイムアウトを設定します。

from urllib import request

response = request.urlopen('data:text/plain,ok', timeout=5)
print(response.read().decode('utf-8'))
ok

WARNING

ネットワーク呼び出しは、さまざまな理由で失敗することがあります。urllib.error.URLError などの例外を処理し、信頼できない URL を取得するときは注意してください。

関連リンク