0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

URLの「?〜」部分、urllib.parseで取り出す方法

Last updated at Posted at 2025-08-01

はじめに

API開発をしていると、URLに含まれるクエリパラメータを取得して、後続の処理に使い回したい場面があります。Pythonでは、標準ライブラリ urllib.parse を使えば、URLのクエリ部分を簡単に解析し、必要なパラメータを取り出すことができます。

urllib.parseとは

urllib.parse は、Pythonの標準ライブラリで、URLを扱うためのモジュールです。
このモジュールを使えば、次のような処理を簡単に実装できます。

  • URLを構成要素(スキーム、ホスト、パス、クエリなど)に分解する
  • クエリパラメータを辞書として取得する
  • クエリパラメータを追加・変更・削除する

使い方

クエリパラメータの取得

例として、次のようなURLからクエリパラメータを取得してみます。

from urllib.parse import urlparse, parse_qs

url = 'https://example.com/search?q=python&sort=desc&page=2'

# URLを構成要素に分解
parsed_url = urlparse(url)

# クエリ部分を辞書に変換
query_params = parse_qs(parsed_url.query)

print(query_params)
# 出力: {'q': ['python'], 'sort': ['desc'], 'page': ['2']}

関数の役割

  • urlparse(url)
    URLを「スキーム(https)」「ホスト名(example.com)」「パス(/search)」「クエリ(q=python&...)」などの要素に分解する関数です。
    戻り値は ParseResult というオブジェクトで、それぞれの要素に簡単にアクセスできます。

  • parse_qs(query)
    クエリ文字列(例: q=python&sort=desc)を辞書形式に変換する関数です。
    値はリストで返されます(例: {'q': ['python']})

parse_qs の戻り値は、値はリスト形式になっています。
単一の値が欲しい場合は次のように取得できます。

q = query_params.get('q', [None])[0]
print(q)  # 出力: 'python'

おわりに

urllib.parse には他にも便利な機能が用意されています。
クエリの組み立てやURLの再構成にもチャレンジしてみると、理解が深まるはずです。

0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?