2022-02-10に投稿

Python 標準ライブラリ urllib.request URLのリクエスト

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

HTTP レスポンスをファイルに保存

リクエストした結果をファイルに保存する場合
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の要求

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()

Postの要求

第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()

Requestを使った要求

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()

UA(ユーザーエージェント)を指定した要求

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とパス名の変換

ファイルパスと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\\;$\\'

参考

Originally published at marusankakusikaku.jp
ツイッターでシェア
みんなに共有、忘れないようにメモ

maru3kaku4kaku

Pythonこつこつ学習中。よく忘れる。

Crieitは誰でも投稿できるサービスです。 是非記事の投稿をお願いします。どんな軽い内容でも投稿できます。

また、「こんな記事が読みたいけど見つからない!」という方は是非記事投稿リクエストボードへ!

有料記事を販売できるようになりました!

こじんまりと作業ログやメモ、進捗を書き残しておきたい方はボード機能をご利用ください。
ボードとは?

コメント