Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'

like image 556
amphibient Avatar asked Nov 11 '16 23:11

amphibient


People also ask

How do you pass special characters in a URL in Python?

s = urllib2. quote(s) # URL encode. # Now "s" is encoded the way you need it. It works!

How do I encode a URL?

Since URLs often contain characters outside the ASCII set, the URL has to be converted into a valid ASCII format. URL encoding replaces unsafe ASCII characters with a "%" followed by two hexadecimal digits. URLs cannot contain spaces. URL encoding normally replaces a space with a plus (+) sign or with %20.


1 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' 
like image 112
Adam Smith Avatar answered Oct 06 '22 23:10

Adam Smith