3

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?

Vermillion
  • 1,238
  • 1
  • 14
  • 29

2 Answers2

5
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)
Mathieu Rollet
  • 2,016
  • 2
  • 18
  • 31
1

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'
That1Guy
  • 7,075
  • 4
  • 47
  • 59