在 Python 2.4 中使用 urllib 解析查询字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1769625/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 23:01:04  来源:igfitidea点击:

parse query string with urllib in Python 2.4

pythonparsingurllib

提问by Johannes Charra

Using Python2.4.5 (don't ask!) I want to parse a query string and get a dict in return. Do I have to do it "manually" like follows?

使用 Python2.4.5(不要问!)我想解析一个查询字符串并得到一个 dict 作为回报。我必须像下面这样“手动”做吗?

>>> qs = 'first=1&second=4&third=3'
>>> d = dict([x.split("=") for x in qs.split("&")])
>>> d
{'second': '4', 'third': '3', 'first': '1'}

Didn't find any useful method in urlparse.

中没有找到任何有用的方法urlparse

回答by P?r Wieslander

You have two options:

您有两个选择:

>>> cgi.parse_qs(qs)
{'second': ['4'], 'third': ['3'], 'first': ['1']}

or

或者

>>> cgi.parse_qsl(qs)
[('first', '1'), ('second', '4'), ('third', '3')]

The values in the dict returned by cgi.parse_qs()are lists rather than strings, in order to handle the case when the same parameter is specified several times:

dict 中返回的值cgi.parse_qs()是列表而不是字符串,以便处理多次指定相同参数的情况:

>>> qs = 'tags=python&tags=programming'
>>> cgi.parse_qs(qs)
{'tags': ['python', 'programming']}

回答by Berry Tsakala

this solves the annoyance:

这解决了烦恼:

d = dict(urlparse.parse_qsl( qs ) )

personally i would expect there two be a built in wrapper in urlparse. in most cases i wouldn't mind to discards the redundant parameter if such exist

我个人希望在 urlparse 中有两个内置包装器。在大多数情况下,如果存在冗余参数,我不介意丢弃冗余参数

回答by Shariq

import urlparse
qs = 'first=1&second=4&third=3&first=0'

print dict(urlparse.parse_qsl(qs))

OR

print urlparse.parse_qs(qs)