gpt4 book ai didi

python - dict python的URL查询参数

转载 作者:IT老高 更新时间:2023-10-28 21:33:47 25 4
gpt4 key购买 nike

有没有办法解析一个 URL(使用一些 python 库)并返回一个 python 字典,其中包含 URL 的查询参数部分的键和值?

例如:

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

预期返回:

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

最佳答案

使用 urllib.parse library :

>>> 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 .

关于python - dict python的URL查询参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21584545/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com