Get Root Domain of Link

Viewed 25991

I have a link such as http://www.techcrunch.com/ and I would like to get just the techcrunch.com part of the link. How do I go about this in python?

9 Answers

You dont need a package, or any of the complexities people are suggesting to do this, it's as simple as below and tweaking to your liking.

def is_root(url):
    head, sep, tail = url.partition('//')
    is_root_domain = tail.split('/', 1)[0] if '/' in tail else url
    # printing or returning is_root_domain will give you what you seek
    print(is_root_domain)

is_root('http://www.techcrunch.com/')

This worked for me:

def get_sub_domains(url):
    urlp = parseurl(url)
    urlsplit = urlp.netloc.split(".")
    l = []
    if len(urlsplit) < 3: return l
    for item in urlsplit:
        urlsplit = urlsplit[1:]
        l.append(".".join(urlsplit))
        if len(urlsplit) < 3:
            return l

this simple code will get the root domain name from all valid URLs.

from urllib.parse import urlparse

url = 'https://www.google.com/search?q=python'
root_url = urlparse(url).scheme + '://' + urlparse(url).hostname
print(root_url) # https://www.google.com
Related