Python3 - parse_qs 没有按预期分隔参数

问题描述 投票:0回答:1

我正在使用Python3中的

urllib
库。代码:

from urllib.parse import parse_qs
parse_qs('https://www.example.com/?api-url=%2Fp%2Ftest-test-test-000761di%3Fajax%3Dtrue&api-params=%3Ft%3Dst-fs%26tc%3Dtrue')

返回字典:

{
  'https://www.example.com/?api-url': ['/p/test-test-test-000761di?ajax=true'], 
  'api-params': ['?t=st-fs&tc=true']
}

有人可以向我解释一下字典是如何构建的吗?

为什么

...?api-url
&api-params
是键,而
?ajax
?t
&tc
不是?我在哪里可以阅读有关该主题的内容?

python python-3.x url urllib
1个回答
1
投票

parse_qs()
需要 只是查询字符串。您传入了完整的 URL。

如果您传入仅查询字符串,您将得到:

>>> parse_qs('api-url=%2Fp%2Ftest-test-test-000761di%3Fajax%3Dtrue&api-params=%3Ft%3Dst-fs%26tc%3Dtrue')
{'api-url': ['/p/test-test-test-000761di?ajax=true'], 'api-params': ['?t=st-fs&tc=true']}

这是给定查询字符串的正确结果;您在输出中看到的

?
=
&
字符在输入查询字符串中已被 转义

例如,

api-params
的转义值为
%3Ft%3Dst-fs%26tc%3Dtrue
;正确的解释是该字符串的不带引号的值,即
'?t=st-fs&tc=true'

然后您可以再次解析这些值,以删除第二层查询字符串语法,但您必须解析出查询字符串: >>> parsed['api-url'][0].partition('?')[-1] 'ajax=true' >>> parse_qs(parsed['api-url'][0].partition('?')[-1]) {'ajax': ['true']} >>> parsed['api-params'][0].partition('?')[-1] 't=st-fs&tc=true' >>> parse_qs(parsed['api-params'][0].partition('?')[-1]) {'t': ['st-fs'], 'tc': ['true']}

我使用 

str.partition()

 来拆分第一个 
? 字符上的字符串,并将第一个字符之后的所有内容解析为查询字符串。
    

© www.soinside.com 2019 - 2024. All rights reserved.