close

How to URL encode in Python 3?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to URL encode in Python 3 in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to URL encode in Python 3?

  1. How to URL encode in Python 3?

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

  2. URL encode in Python 3

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

Method 1

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'

Method 2

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'

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read