How To Encode URL and Query String In Python?

URL or Uniform Resource Locator is a technology and standard used to define different digital resources. The URL is well known with the web site addresses like https://www.pythontect.com. Python provides different methods in order to encode the URL properly in order to form it in a global form.

Python URL Encode Methods

Python provides the following methods in order to encode a URL or query string.

  • quote() Method
  • urlencode() Method

Encode URL with quote() Method

Python provides the quote() method which will encodethe provided string. The quote() method is provided by the urllib.parse module which is a built-in module. There is not need to install this module just importing it will work.

import urllib.parse

URL = "https://www.pythontect.com/about/?name=ismail&pass=123"

encoded_URL = urllib.parse.quote(URL)

print(encoded_URL)

The encoded URL which will be printed to the standard output will be like below.

https%3A//www.pythontect.com/about/%3Fname%3Dismail%26pass%3D123

As we can see from the encoded URL some signs like / do not encode into different characters. But there is a way that encodes the URL safer by encoding all non-alphabet characters. The safe parameter can be set empty string which will convert all non-alphabet characters.

import urllib.parse

URL = "https://www.pythontect.com/about/?name=ismail&pass=123"

encoded_URL = urllib.parse.quote(URL,safe="")

print(encoded_URL)

The output will be like below.

https%3A%2F%2Fwww.pythontect.com%2Fabout%2F%3Fname%3Dismail%26pass%3D123

Encode URL or Query String with urlencode() Method

Another method to encode a URL is the urlencode() method which is provided via urllib.parse module too. As a built-in module just importing the urllib.parse module will work without problem. URL encode especially used for encoding query strings where they consist of key-value pairs which is very same with the dictionary items. The parameters are provided as dictionary to the urlencode() method.

import urllib.parse

query_string = { "username":"ismail baydan" , "password":"123"}

encoded_URL = urllib.parse.urlencode( query_string )

print(encoded_URL)

The output will be like below.

username=ismail+baydan&password=123

Leave a Comment