[Python] Best way to parse a URL query string

python 3 解法:

Here is an example using python3 urllib.parse:

from urllib.parse import urlparse, parse_qs
URL='https://someurl.com/with/query_string?i=main&mode=front&sid=12ab&enc=+Hello'
parsed_url = urlparse(URL)
parse_qs(parsed_url.query

python 3 官方文件:
https://docs.python.org/3/library/urllib.parse.html


python 2 解法:

from urlparse import urlparse, parse_qs

python 2 官方文件:
https://docs.python.org/2/library/urlparse.html


相容於 python 2 + python 3 解法:

# Python 2 and 3
    try:
        # python3 urllib.parse:
        from urllib.parse import urlparse, parse_qs
    except ImportError:
        from urlparse import urlparse, parse_qs

    parsed_url = urlparse(url)
    qstr=parse_qs(parsed_url.query)

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *