does python requests encode url

Does Python Requests Encode URL?

Yes, Python requests module does encode URL automatically by default.

Explanation

When a URL is requested via Python requests module, the requests library automatically encodes the URL with the appropriate character encoding. This is useful because URLs can contain special characters such as spaces, quotation marks, and more which need to be encoded in order for the URL to be properly parsed by web servers and applications.

For instance, let's say we have a URL:

https://example.com/search?q=python requests

The space character between "python" and "requests" should be encoded as "%20" for the URL to work properly. Python requests module encodes this URL automatically when we make a request:


import requests

url = 'https://example.com/search'
params = {'q': 'python requests'}

response = requests.get(url, params=params)

print(response.url)

The above code will automatically encode the URL with the appropriate character encoding.

Alternate Method

If we don't want Python requests to automatically encode the URL, we can pass the URL as a raw string:


import requests

url = r'https://example.com/search?q=python requests'

response = requests.get(url)

print(response.url)

The "r" before the URL string tells Python to treat it as a raw string and not perform any escape characters on it. This will prevent Python requests from automatically encoding the URL.