[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)

相關文章

寫留言

你的電子郵件位址並不會被公開。 必要欄位標記為 *