URL 查询参数到 dict python [英] URL query parameters to dict python

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

问题描述

有没有办法解析一个 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:

<预><代码>>>>从 urllib 导入解析>>>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)){'项目':'98','操作':'92','ct':'32'}

urllib.parse.parse_qs()urllib.parse.parse_qsl() 方法解析出查询字符串,考虑到键可以出现多次并且这个顺序可能很重要.

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

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?

For example:

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

expected return:

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

解决方案

Use the 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'}

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.

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

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

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