如何在 Python 中对查询字符串进行 urlencode?

新手上路,请多包涵

我正在尝试在提交之前对这个字符串进行 urlencode。

 queryString = 'eventName=' + evt.fields["eventName"] + '&' + 'eventDescription=' + evt.fields["eventDescription"];

原文由 James 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 432
2 个回答

您需要将参数传递给 urlencode() 作为映射 (dict) 或 2 元组序列,例如:

 >>> import urllib
>>> f = { 'eventName' : 'myEvent', 'eventDescription' : 'cool event'}
>>> urllib.urlencode(f)
'eventName=myEvent&eventDescription=cool+event'

Python 3 或以上

使用 urllib.parse.urlencode

 >>> urllib.parse.urlencode(f)
eventName=myEvent&eventDescription=cool+event

请注意,这 不会 在常用意义上进行 url 编码(查看输出)。为此使用 urllib.parse.quote_plus

原文由 bgporter 发布,翻译遵循 CC BY-SA 4.0 许可协议

蟒蛇2

你要找的是 urllib.quote_plus

 safe_string = urllib.quote_plus('string_of_characters_like_these:$#@=?%^Q^$')

#Value: 'string_of_characters_like_these%3A%24%23%40%3D%3F%25%5EQ%5E%24'

蟒蛇3

在 Python 3 中, urllib 包被分解成更小的组件。您将使用 urllib.parse.quote_plus (注意 parse 子模块)

 import urllib.parse
safe_string = urllib.parse.quote_plus(...)

原文由 Ricky Sahu 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题