🛠️ToolsShed

URL / URI パーサー

URLをプロトコル・ホスト・パス・クエリ・ハッシュに分解。

よくある質問

コード実装

from urllib.parse import urlparse, parse_qs, urlencode, quote

url = "https://user:pass@example.com:8080/path/to/page?foo=1&bar=two&bar=three#section"

parsed = urlparse(url)
print(parsed.scheme)    # https
print(parsed.netloc)    # user:pass@example.com:8080
print(parsed.hostname)  # example.com
print(parsed.port)      # 8080
print(parsed.path)      # /path/to/page
print(parsed.query)     # foo=1&bar=two&bar=three
print(parsed.fragment)  # section

# Parse query string into dict (lists for repeated keys)
params = parse_qs(parsed.query)
print(params)  # {'foo': ['1'], 'bar': ['two', 'three']}

# URL-encode a value
encoded = quote("hello world & more")
print(encoded)  # hello%20world%20%26%20more

Comments & Feedback

Comments are powered by Giscus. Sign in with GitHub to leave a comment.