Python urllib.parse does not have a nice method to set/edit or remove username/password from URLs.
However, you can use the netloc
attribute. See the example function below.
from urllib.parse import urlparse, quote
def set_url_username_password(url, username, password):
_username = quote(username)
_password = quote(password)
_url = urlparse(url)
_netloc = _url.netloc.split('@')[-1]
_url = _url._replace(netloc=f'{_username}:{_password}@{_netloc}')
return _url.geturl()
original_url = 'https://google.com'
username = 'username'
password = 'pa$$word'
new_url = set_url_username_password(original_url, username, password)
new_url
will be set to https://username:pa%24%[email protected]
.
Note that this function replaces any existing credentials with the new ones.
Here is a bonus function to remove credentials from an URL:
from urllib.parse import urlparse
def unset_url_username_password(url):
_url = urlparse(url)
_netloc = _url.netloc.split('@')[-1]
_url = _url._replace(netloc=_netloc)
return _url.geturl()
url_text.replace('https://', 'https://user@pass')
– Balladist