Python標準のライブラリurllib.requestを使うとURLをリクエストして結果を取得することができます。
以下のようにURLを指定して結果を取得できます。
import urllib.request
with urllib.request.urlopen('https://example.jp/') as response:
html = response.read()
url = response.geturl()
info = response.info()
HTTPSでSSL認証のエラーが発生する場合、以下を指定することで回避できる。
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
リクエストした結果をファイルに保存する場合
shutil.copyfileobj
が使えます。
import shutil
with urllib.request.urlopen('https://example.jp/') as response:
with open('./request_out.html', mode="bw") as f:
shutil.copyfileobj(response, f)
要求の応答でエラーがある場合は、HTTPErrorやURLErrorでその内容を取得できる。
html = ''
try:
with urllib.request.urlopen('https://example.jp') as response:
html = response.read()
except urllib.error.HTTPError as e:
print(e)
print(e.code)
print(e.reason)
except urllib.error.URLError as e:
print(e)
print(e.code)
print(e.reason)
else:
print(html)
Getの要求は直接クエリーパラメータをURLに指定できる。
with urllib.request.urlopen('https://example.jp/sample?key=value') as response:
html = response.read()
urllib.parseのurlencodeを使うと、
マッピング型のオブジェクトからURLエンコードされたクエリーパラメータを取得できます。
data = {}
data['key1'] = 'value1'
data['key2'] = 'value2'
query = urllib.parse.urlencode(data)
print(query) # => key1=value1&key2=value2
with urllib.request.urlopen('https://example.jp/sample?' + query) as response:
html = response.read()
第2引数(data)を指定するとPOSTで要求が行われます。
data = {}
data['key1'] = 'value1'
data['key2'] = 'value2'
data_string = urllib.parse.urlencode(data)
data_string = data_string.encode('ascii')
print(data_string) # => b'key1=value1&key2=value2'
with urllib.request.urlopen('https://example.jp/sample',data=data_string) as response:
html = response.read()
urlopenには、リクエスト型のパラメータを指定することもできます。
req = urllib.request.Request('https://example.jp/')
with urllib.request.urlopen(req) as response:
html = response.read()
Requestの第2引数を指定し、それをurlopenに渡すことでPOSTの要求ができる。
data = {}
data['key1'] = 'value1'
data['key2'] = 'value2'
data_string = urllib.parse.urlencode(data)
data_string = data_string.encode('ascii')
print(data_string) # => b'key1=value1&key2=value2'
req = urllib.request.Request('https://example.jp/sample', data_string)
with urllib.request.urlopen(req) as response:
html = response.read()
user_agent = "Mozilla/5.0 (Linux; Android 4.4; Nexus 5 Build/_BuildID_) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/30.0.0.0 Mobile Safari/537.36"
req = urllib.request.Request('https://example.jp/search?q=test', headers={'User-Agent': user_agent}, method='GET')
with urllib.request.urlopen(req) as response:
html = response.read()
ファイルパスとURLパスを相互に変換するための関数が用意されている。
urllib.request.pathname2url('/path/to/a=b+c&d=e f/[email protected]/x,y/;$/')
# => '/path/to/a%3Db%2Bc%26d%3De%20f/user%40example.com/x%2Cy/%3B%24/'
urllib.request.url2pathname('/path/to/a%3Db%2Bc%26d%3De%20f/user%40example.com/x%2Cy/%3B%24/')
# => '\\path\\to\\a=b+c&d=e f\\[email protected]\\x,y\\;$\\'
Crieitは誰でも投稿できるサービスです。 是非記事の投稿をお願いします。どんな軽い内容でも投稿できます。
また、「こんな記事が読みたいけど見つからない!」という方は是非記事投稿リクエストボードへ!
こじんまりと作業ログやメモ、進捗を書き残しておきたい方はボード機能をご利用ください。
ボードとは?
コメント