Learn how to get the base URL of a full URL in Python
To get the base URL of a full URL string in Python, you can use the urlsplit function from the urllib.parse module.
The urlsplit() function returns segments of your URL as an object:
To get the base URL from the url_parts result, you can concatenate the scheme and netloc parts together with a :// between them.
If you only need the domain name, then you can access the netloc section:
Next, suppose you want to get the base URL up until before the last section.
You can use the str.rsplit() method and remove just the last part as follows:
And that’s how you get the base URL using Python. If you want to get the base URL or just the domain, you can use the urlsplit() function.
To get the base URL up to before the last segment, you can use the rsplit() method.
I’ve also written additional tutorials that explain how to work with URLs in Python:
I hope these tutorials are helpful in your Python programming journey. See you in other tutorials! 👋
Take your skills to the next level ⚡️
I’m sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I’ll send new stuff straight into your inbox!
About
Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.
Search
Type the keyword below and hit enter
Tags
Click to see all tutorials tagged with: