How to urlencode a querystring in Python?

后端 未结 13 1723
猫巷女王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:37

    for future references (ex: for python3)

    >>> import urllib.request as req
    >>> query = 'eventName=theEvent&eventDescription=testDesc'
    >>> req.pathname2url(query)
    >>> 'eventName%3DtheEvent%26eventDescription%3DtestDesc'
    
    0 讨论(0)
  • 2020-11-22 11:38

    For use in scripts/programs which need to support both python 2 and 3, the six module provides quote and urlencode functions:

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

    If the urllib.parse.urlencode( ) is giving you errors , then Try the urllib3 module .

    The syntax is as follows :

    import urllib3
    urllib3.request.urlencode({"user" : "john" }) 
    
    0 讨论(0)
  • 2020-11-22 11:44

    Try this:

    urllib.pathname2url(stringToURLEncode)
    

    urlencode won't work because it only works on dictionaries. quote_plus didn't produce the correct output.

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

    In Python 3, this worked with me

    import urllib
    
    urllib.parse.quote(query)
    
    0 讨论(0)
  • 2020-11-22 11:50

    Python 2

    What you're looking for is urllib.quote_plus:

    >>> urllib.quote_plus('string_of_characters_like_these:$#@=?%^Q^$')
    'string_of_characters_like_these%3A%24%23%40%3D%3F%25%5EQ%5E%24'
    

    Python 3

    In Python 3, the urllib package has been broken into smaller components. You'll use urllib.parse.quote_plus (note the parse child module)

    import urllib.parse
    urllib.parse.quote_plus(...)
    
    0 讨论(0)
提交回复
热议问题