[Python] URLlib3の使い方

urllib3はPython用のHTTPクライアントで、Python標準ライブラリより多くの機能を搭載しています。MITライセンスの元で利用可能です。

urllib3のインポート

//ubuntuの場合
$ sudo apt install urllib3

//pipでのインストールの場合
$ pip install urllib3

リクエストの作成

urllib3モジュールをインポートして、インスタンスを作成します。

import urllib3
http = urllib3.PoolManager()

リクエストの作成

url = 'https://www.example.com'
response = http.request('GET', url)
print(response.data.decode('utf-8'))

Basic認証でID/PASSを自動入力する例

id = "IDを入力"
pw = "Passwordを入力"

import urllib3
http = urllib3.PoolManager()

url = "https://www.example.com"
headers = urllib3.util.make_headers(basic_auth="%s:%s" % (id, pw) )
response = http.request("GET", url, headers=headers)

//ファイルに保存
f = open("test.csv", "wb")
f.write(response.data)
f.close()

//単純に表示
print(response.data.decode('utf-8'))


Author: webmaster