amphibient amphibient - 22 days ago 8
Python Question

How to URL encode in Python 3?

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'

Answer

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'
Comments