用于dict python的URL查询参数 [英] URL query parameters to dict python

查看:145
本文介绍了用于dict python的URL查询参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以解析URL(带有一些python库)并返回一个python字典,其中包含URL的查询参数部分的键和值?

Is there a way to parse a URL (with some python library) and return a python dictionary with the keys and values of a query parameters part of the URL?

例如:

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()方法解析出查询字符串,并考虑到键可以出现多次,并且顺序可能很重要.

The urllib.parse.parse_qs() and urllib.parse.parse_qsl() methods parse out query strings, taking into account that keys can occur more than once and that order may matter.

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

If you are still on Python 2, urllib.parse was called urlparse.

这篇关于用于dict python的URL查询参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆