如何在Python中进行querystring的url编码?

772 投票
15 回答
1099083 浏览
提问于 2025-04-16 15:24

我在提交之前想对这个字符串进行URL编码。

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

15 个回答

99

试试用requests,而不是urllib,这样你就不用再为url编码烦恼了!

import requests
requests.get('http://youraddress.com', params=evt.fields)

编辑:

如果你需要有顺序的名称-值对或者一个名称对应多个值,可以这样设置参数:

params=[('name1','value11'), ('name1','value12'), ('name2','value21'), ...]

而不是使用字典。

1309

Python 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'

Python 3

在Python 3中,urllib这个包被拆分成了几个小部分。你会使用 urllib.parse.quote_plus(注意这里有个parse的子模块)

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

你需要把参数传递给 urlencode(),可以用字典(dict)或者一对对的元组(2-tuples)来传递,像这样:

>>> 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

撰写回答