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

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

当前回答

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(注意解析子模块)

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

其他回答

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

语法如下:

import urllib3
urllib3.request.urlencode({"user" : "john" }) 

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

对于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!

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

编辑:

如果你需要有序的名称-值对或多个名称值,那么设置参数如下:

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

而不是用字典。

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(注意解析子模块)

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