In Python 3+, one can URL-encode any string using the urllib.parse.quote()
(alternatively, you could use requests.utils.quote()
, which is essentially using the same quote()
function from urllib.parse
module). This function is intended for quoting the path section of a URL, not the whole URL. It will essentially replace any special characters in a string using the %xx
escape. In Python 2.x, the quote()
function can be accessed directly from the urllib
package, i.e., urllib.quote()
.
Note that the quote()
function considers /
characters safe by default. Hence, in case you are passing another URL to the path section (or the query string) of the URL and would like to encode /
characters as well, you could do so by setting the safe
parameter to ''
, i.e., an empty string.
Example
import requests
from urllib.parse import quote
base_url = 'https://example.com/'
path_param = 'https://raw.githubusercontent.com/ultralytics/yolov5/master/data/images/zidane.jpg'
url = base_url + quote(path_param, safe='')
r = requests.get(url)
print(r.request.url)