python urlparse get domain 1

python urlparse get domain

from urllib.parse import urlparse

domain = urlparse('http://www.example.test/foo/bar').netloc
print(domain) # --> www.example.test

#To get without the subdomain
t = urlparse('http://abc.hostname.com/somethings/anything/').netloc
print ('.'.join(t.split('.')[1:])) # --> hostname.com

Here is what the above code is Doing:
1. urlparse(‘http://abc.hostname.com/somethings/anything/’).netloc
–> ‘abc.hostname.com’
2. t.split(‘.’)
–> [‘abc’, ‘hostname’, ‘com’]
3. [‘abc’, ‘hostname’, ‘com’][1:]
–> [‘hostname’, ‘com’]
4. ‘.’.join([‘hostname’, ‘com’])
–> ‘hostname.com’

Similar Posts