How to encode URL parameters in Python?

Published on Aug. 22, 2023, 12:17 p.m.

There are several ways to encode URL parameters in Python, such as using the urllib.parse.urlencode() function or the requests library. Here’s an example using urllib.parse.urlencode():

import urllib.parse

params = {'param1': 'value1', 'param2': 'value2'}
encoded_params = urllib.parse.urlencode(params)
url = 'https://www.example.com?' + encoded_params

In this example, we create a dictionary of parameters, then use urllib.parse.urlencode() to encode the parameters into a URL-safe string. Finally, we can append the encoded parameters to the base URL to create the full URL for the request.

Another way to do this is to use the requests library, which provides a more convenient way to make HTTP requests and encode URL parameters:

import requests

params = {'param1': 'value1', 'param2': 'value2'}
url = 'https://www.example.com'
response = requests.get(url, params=params)

In this example, we create a dictionary of parameters, then pass it to the params argument of the requests.get() function. The requests library automatically encodes the parameters and adds them to the URL for the GET request.

Tags:

url