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%20moreComments & Feedback
Comments are powered by Giscus. Sign in with GitHub to leave a comment.