Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change hostname of URL with urllib

I want to change the hostname of a URL.

>>> import urllib


>>> url = "https://foo.bar.com:9300/hello"

>>> parsed = urllib.parse.urlparse(url)

>>> parsed
ParseResult(scheme='https', netloc='foo.bar.com:9300', path='/hello', params='', query='', fragment='')

Because parsed is a namedtuple, the scheme can be replaced:

>>> parsed_replaced = parsed._replace(scheme='http')

>>> urllib.parse.urlunparse(parsed_replaced)
'http://foo.bar.com:9300/hello'

The parsed object also has an attribute for the hostname:

>>> parsed.hostname
'foo.bar.com'

But it's not one of the fields in the namedtuple, so it can't be replaced like the scheme.

Is there a way to replace just the hostname in the URL?

like image 799
Vermillion Avatar asked Sep 18 '25 06:09

Vermillion


2 Answers

import urllib.parse

url = "https://foo.bar.com:9300/hello"
parsed = urllib.parse.urlparse(url)
hostname = parsed.hostname
new_hostname = "my.new.hostname"

parsed_replaced = parsed._replace(netloc=parsed.netloc.replace(hostname, new_hostname))

print(parsed_replaced)
like image 53
Mathieu Rollet Avatar answered Sep 19 '25 18:09

Mathieu Rollet


You're looking for netloc

url = 'https://foo.bar.com:9300/hello'
parsed = urllib.parse.urlparse(url)
parsed_replaced = parsed._replace(netloc='spam.eggs.com:9300')

urllib.parse.urlunparse(parsed_replaced)
'https://spam.eggs.com:9300/hello'
like image 43
That1Guy Avatar answered Sep 19 '25 20:09

That1Guy