字典python的URL查询参数


问题内容

有没有办法解析URL(带有某些python库)并返回带有URL的查询参数部分的键和值的python字典?

例如:

url = "http://www.example.org/default.html?ct=32&op=92&item=98"

预期收益:

{'ct':32, 'op':92, 'item':98}

问题答案:

使用urllib.parse

>>> from urllib import parse
>>> url = "http://www.example.org/default.html?ct=32&op=92&item=98"
>>> parse.urlsplit(url)
SplitResult(scheme='http', netloc='www.example.org', path='/default.html', query='ct=32&op=92&item=98', fragment='')
>>> parse.parse_qs(parse.urlsplit(url).query)
{'item': ['98'], 'op': ['92'], 'ct': ['32']}
>>> dict(parse.parse_qsl(parse.urlsplit(url).query))
{'item': '98', 'op': '92', 'ct': '32'}

urllib.parse.parse_qs()urllib.parse.parse_qsl()方法解析出查询字符串,考虑到钥匙可能会出现不止一次和顺序可能无关紧要。

如果您仍在使用Python
2,urllib.parse则称为urlparse