Search code examples
pythonpython-3.xurlurlliburlparse

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?


Solution

  • 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)