How to urlencode a querystring in Python?

后端 未结 13 1721
猫巷女王i
猫巷女王i 2020-11-22 11:19

I am trying to urlencode this string before I submit.

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


        
相关标签:
13条回答
  • 2020-11-22 11:25

    Python 3:

    urllib.parse.quote_plus(string, safe='', encoding=None, errors=None)

    0 讨论(0)
  • 2020-11-22 11:26

    Try requests instead of urllib and you don't need to bother with urlencode!

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

    EDIT:

    If you need ordered name-value pairs or multiple values for a name then set params like so:

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

    instead of using a dictionary.

    0 讨论(0)
  • 2020-11-22 11:29

    Another thing that might not have been mentioned already is that urllib.urlencode() will encode empty values in the dictionary as the string None instead of having that parameter as absent. I don't know if this is typically desired or not, but does not fit my use case, hence I have to use quote_plus.

    0 讨论(0)
  • 2020-11-22 11:31

    For Python 3 urllib3 works properly, you can use as follow as per its official docs :

    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')
    
    0 讨论(0)
  • 2020-11-22 11:35

    Note that the urllib.urlencode does not always do the trick. The problem is that some services care about the order of arguments, which gets lost when you create the dictionary. For such cases, urllib.quote_plus is better, as Ricky suggested.

    0 讨论(0)
  • 2020-11-22 11:36

    You need to pass your parameters into urlencode() as either a mapping (dict), or a sequence of 2-tuples, like:

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

    Python 3 or above

    Use:

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

    Note that this does not do url encoding in the commonly used sense (look at the output). For that use urllib.parse.quote_plus.

    0 讨论(0)
提交回复
热议问题