0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Python初心者】URLを解析・構築・エンコードする基本まとめ

Posted at

PythonでURLを扱うときに使う標準ライブラリ urllib.parse の機能について学んだことを、自分用の学習メモとしてまとめました。URLの分解や結合、クエリの操作、エンコードなど、よく使う基本を整理しています。

URLを構成要素に分解する(urlparse()

URLをスキーム・ドメイン・パス・クエリなどに分解するには urlparse() を使います。

from urllib.parse import urlparse

url = "https://example.com/path/to/page?name=alice&age=30"
parsed = urlparse(url)

print(parsed.scheme)   # 'https'
print(parsed.netloc)   # 'example.com'
print(parsed.path)     # '/path/to/page'
print(parsed.query)    # 'name=alice&age=30'
https
example.com
/path/to/page
name=alice&age=30

クエリ文字列を辞書形式に変換する(parse_qs()

URLのクエリ文字列を辞書のように扱うには parse_qs() を使います。返される値はリスト型です。

from urllib.parse import parse_qs

query = "name=alice&age=30&age=25"
params = parse_qs(query)

print(params)
{'name': ['alice'], 'age': ['30', '25']}

クエリ文字列をタプルのリストにする(parse_qsl()

クエリの順番を保持した(キー, 値)のリストが欲しいときは parse_qsl() を使います

from urllib.parse import parse_qsl

query = "name=alice&age=30&age=25"
params = parse_qsl(query)

print(params)
[('name', 'alice'), ('age', '30'), ('age', '25')]

辞書からクエリ文字列を作る(urlencode()

辞書などのデータをURLのクエリ文字列に変換するには urlencode() を使います。

from urllib.parse import urlencode

params = {'name': 'alice', 'age': 30}
query_string = urlencode(params)

print(query_string)
name=alice&age=30

リストの値を含む場合、doseq=True を指定すると複数キーになります。

params = {'age': [30, 25]}
print(urlencode(params, doseq=True))
age=30&age=25

URLエンコードとデコード(quote() / unquote()

URLに使えない文字(日本語など)を含む文字列は、エンコードして安全に送れるようにします。

from urllib.parse import quote, unquote

original = "こんにちは"
encoded = quote(original)
decoded = unquote(encoded)

print(encoded)
print(decoded)
%E3%81%93%E3%82%93%E3%81%AB%E3%81%A1%E3%81%AF
こんにちは

相対URLを組み立てる(urljoin()

ベースとなるURLに対して相対パスを組み合わせて、絶対URLを作ることができます。

from urllib.parse import urljoin

base = "https://example.com/path/"
relative = "sub/page.html"
full_url = urljoin(base, relative)

print(full_url)
https://example.com/path/sub/page.html

おわりに

今回はURLの構造を理解したり、クエリや文字列のエンコード・デコードをするための基本的な使い方を整理しました

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?