How to URL encode in Python 3?

前端 未结 3 975
夕颜
夕颜 2020-12-13 12:32

I have tried to follow the documentation but was not able to use urlparse.parse.quote_plus() in Python 3:

from urllib.parse import          


        
相关标签:
3条回答
  • 2020-12-13 12:35

    You’re looking for urllib.parse.urlencode

    import urllib.parse
    
    params = {'username': 'administrator', 'password': 'xyz'}
    encoded = urllib.parse.urlencode(params)
    # Returns: 'username=administrator&password=xyz'
    
    0 讨论(0)
  • 2020-12-13 12:41

    For Python 3 you could try using quote instead of quote_plus:

    import urllib.parse
    
    print(urllib.parse.quote("http://www.sample.com/"))
    

    Result:

    http%3A%2F%2Fwww.sample.com%2F
    

    Or:

    from requests.utils import requote_uri
    requote_uri("http://www.sample.com/?id=123 abc")
    

    Result:

    'https://www.sample.com/?id=123%20abc'
    
    0 讨论(0)
  • 2020-12-13 13:01

    You misread the documentation. You need to do two things:

    1. Quote each key and value from your dictionary, and
    2. Encode those into a URL

    Luckily urllib.parse.urlencode does both those things in a single step, and that's the function you should be using.

    from urllib.parse import urlencode, quote_plus
    
    payload = {'username':'administrator', 'password':'xyz'}
    result = urlencode(payload, quote_via=quote_plus)
    # 'password=xyz&username=administrator'
    
    0 讨论(0)
提交回复
热议问题