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

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

当前回答

为了在需要同时支持python 2和3的脚本/程序中使用,six模块提供了quote和urlencode函数:

>>> from six.moves.urllib.parse import urlencode, quote
>>> data = {'some': 'query', 'for': 'encoding'}
>>> urlencode(data)
'some=query&for=encoding'
>>> url = '/some/url/with spaces and %;!<>&'
>>> quote(url)
'/some/url/with%20spaces%20and%20%25%3B%21%3C%3E%26'

其他回答

对于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.pathname2url(stringToURLEncode)

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

如果urllib.parse. parse。urlencode()给你错误,然后尝试urllib3模块。

语法如下:

import urllib3
urllib3.request.urlencode({"user" : "john" }) 
import urllib.parse
query = 'Hellö Wörld@Python'
urllib.parse.quote(query) // returns Hell%C3%B6%20W%C3%B6rld%40Python

你需要将你的参数传递给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。