urlopen()
python.py
from urllib.request import urlopen
f = urlopen("https://www.googl.co.jp")
print(type(f))
>>> <class http.client.HTTPResponse>
f.read()
#read()メソッドでHTTPレスポンスのボディをbytes型で取得
text = f.read().decode("utf-8")
#文字列型にするには.decode()の引数にエンコーディングを指定
print(type(text))
>>> <class str>
Webページのエンコーディングを取得
python.py
from urllib.request import urlopen
f = urlopen("https://www.googl.co.jp")
encoding = f.info().get_content_charset(failobj="utf-8")
#.info()でHTTPMessageオブジェクトを取得
#.get_content_charser()でcharserの値を取得 引数のfailobjは明示されていない場合のエンコーディング
text = f.read().decode(encoding)
print(text)
#文字列に変換