【问题标题】:Python urllib encoded url has an extra characterPython urllib 编码的 url 有一个额外的字符
【发布时间】:2021-07-21 08:22:42
【问题描述】:

我正在尝试从 python 的 urllib 编码这个列表。

>>> from urllib.parse import urlencode, unquote
>>> data_to_encode = {'user_ids': [1, 2, 3]}
>>> encoded_url = urlencode(data_to_encode)
>>> 
>>> encoded_url
'user_ids=%5B1%2C+2%2C+3%5D'
>>>
>>> unqoute(encoded_url)
'user_ids=[1,+2,+3]'

编码是在元素中插入一个额外的+ 符号。为什么会发生这种情况,我该如何解决这个问题,以便我编码前和解码后的 url 相同?

【问题讨论】:

  • 因为urlencode 将空格编码为+,但取消引用仅将%.. 序列替换回字符,而不是将+ 替换为空格。 ——相反,你期待什么?你想做什么?
  • @deceze 数字上没有前导空格。我玩过,得到了这个:>>> data_to_encode = {'user_ids':['1','2','3']} >>> encoded_url = urlencode(data_to_encode) >>> unquote(encoded_url) "user_ids=['1',+'2',+'3']" >>>
  • @James 不知道你想说什么。列表中的repr 被编码,即[1, 2, 3] 转换为字符串'[1, 2, 3]',其中包含空格,编码为+
  • 我最终做到了——希望我的回答能解释 + 的来源。

标签: python url urllib urlencode


【解决方案1】:

发生这种情况是因为 list 的 __str__ 方法返回由 ", " 连接的列表中的项目,", " 是一个逗号后跟一个空格。当您将列表 [1,2,3] 传递给 urlencode 时,它​​会隐式调用 __str__ 方法来获取字符串表示形式。

>>> data_to_encode['user_ids'].__str__()
"[1, 2, 3]"
>>> ['apple','orange','pear'].__str__()
"['apple', 'orange', 'pear']"

你可以试试unquote_plus

urllib.parse.unquote_plus(string, encoding='utf-8', errors='replace') 与 unquote() 类似,但也根据需要将加号替换为空格 用于取消引用 HTML 表单值。

【讨论】:

    猜你喜欢
    • 2015-07-05
    • 1970-01-01
    • 2012-09-25
    • 1970-01-01
    • 1970-01-01
    • 2015-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多