我试图在提交之前urlencode这个字符串。

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

当前回答

试试这个:

urllib.pathname2url(stringToURLEncode)

Urlencode不能工作,因为它只对字典有效。Quote_plus没有产生正确的输出。

其他回答

对于Python 3 urllib3正常工作,您可以根据其官方文档使用以下方法:

import urllib3

http = urllib3.PoolManager()
response = http.request(
     'GET',
     'https://api.prylabs.net/eth/v1alpha1/beacon/attestations',
     fields={  # here fields are the query params
          'epoch': 1234,
          'pageSize': pageSize 
      } 
 )
response = attestations.data.decode('UTF-8')

另一件可能还没有提到的事情是urllib.urlencode()将字典中的空值编码为字符串None,而不是将该形参作为不存在的参数。我不知道这是否是通常需要的,但不适合我的用例,因此我必须使用quote_plus。

在Python 3中,这对我来说很有效

import urllib

urllib.parse.quote(query)

注意urllib。Urlencode并不总是能做到这一点。问题在于,有些服务关心参数的顺序,而在创建字典时,这些顺序就会丢失。对于这种情况,使用urllib。正如Ricky建议的那样,quote_plus更好。

供以后参考(例如:For python3)

>>> import urllib.request as req
>>> query = 'eventName=theEvent&eventDescription=testDesc'
>>> req.pathname2url(query)
>>> 'eventName%3DtheEvent%26eventDescription%3DtestDesc'