How to URL encode in Python 3?

Question:

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

from urllib.parse import urlparse

params = urlparse.parse.quote_plus({'username': 'administrator', 'password': 'xyz'})

I get

AttributeError: ‘function’ object has no attribute ‘parse’

Asked By: amphibient

||

Answers:

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'
Answered By: Adam Smith

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'
Answered By: rumpel

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

import urllib.parse

print(urllib.parse.quote("http://www.sample.com/", safe=""))

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'
Answered By: Rich Rajah

I have the magic version of Python3 I guess

Python 3.9.2 (default, Feb 28 2021, 17:03:44) 
[GCC 10.2.1 20210110] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import urllib.parse
>>> print(urllib.parse.quote("What the heck this is a test!"))
What%20the%20heck%20this%20is%20a%20test%21
>>> 
Answered By: Walt Howard
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.