Today we are going out to find the domain name out of the URL string through Python. There is a similar Kata in Codewars to extract the domain name from a URL through Python.
Let’s say we have the URL string which is https://hecodesit.com/ What would be the domain name of this URL? The domain name will be hecodesit.
The URL string has 4 main parts.
The first Part is Protocol, a Protocol is rules to transfer data. The most common protocols used in today’s era are HTTPs and HTTP. To know about the difference between HTTP and HTTPs visit HERE.
The Second Part is Subdomain, it is actually a part of the domain. For e.g, my site offers things to sell and I want a shop for my site, in order to do so, I create a subdomain with the same domain name https://shop.hecodesit.com where the shop is a subdomain. To know more about the Subdomain visit HERE.
The Third Part is the Domain Name, It is also known as Root Domain. The domain name is the identification of your site. It is always unique, two people can’t have the same Domain name. To know more about it visit HERE
The Fourth Part is the Top Level Domain, It often describes the purpose of the website. For e.g, if the Top-level Domain is .org we identify the site as an Organization site if a site ends with .com we identify it as a commercial site, etc. To know more about the Top Level Domains visit HERE
Now let’s get to the coding part to extract the Domain out of the URL.
Python Requests get Domain
Question: Write a python program to extract the domain name from the given URL
//Taking input from User. a Url String input_string = input("Enter the site ") //Domain name to Store The Returned Value Domain_name = "" //Split the input string by backslash x = input_string.split("/") //if input URL string contain HTTPs or HTTP if(x == "https:" or x == "http:"): x = x.split(".") //if Input URL String only contain www. without any Http or https. else: x = x.split(".") //if input URL without www. or subdomain if(len(x) == 2): Domain_name = x //if input URL is with www. or subdomain else: Domain_name = x print("The Domain Name is ", Domain_name)
Enter the site www.google.com The Domain Name is google Enter the site https://www.google.com The Domain Name is google Enter the site http://www.google.com The Domain Name is google Enter the site hecodesit.com The Domain Name is hecodesit Enter the site https://hecodesit.com The Domain Name is hecodesit Enter the site http://hecodesit.com The Domain Name is hecodesit
Python-related posts Visit HERE
C++ related posts Visit HERE
Databases related posts Visit HERE
Data Structures related posts visit HERE
Algorithms related posts visit HERE
Data Science related posts visit HERE