Check for URL in a String - Python
Last Updated :
12 Apr, 2025
We are given a string that may contain one or more URLs and our task is to extract them efficiently. This is useful for web scraping, text processing, and data validation. For example:
Input:
s = "My Profile: https://auth.geeksforgeeks.org/user/Prajjwal%20/articles in the portal of https://www.geeksforgeeks.org/"
Output:
['https://auth.geeksforgeeks.org/user/Rayyyyy%20/articles', 'https://www.geeksforgeeks.org/']
Using re.findall()
Python’s Regular Expressions (regex) module allows us to extract patterns like URLs from texts, it comes with various functions like findall(). The re.findall() function in Python is used to find all occurrences of a pattern in a given string and return them as a list.
Python
import re
s = 'My Profile: https://auth.geeksforgeeks.org/user/Rayyyy%20/articles in the portal of https://www.geeksforgeeks.org/'
pattern = r'https?://\S+|www\.\S+'
print("URLs:", re.findall(pattern, s))
OutputURLs: ['https://auth.geeksforgeeks.org/user/Rayyyy%20/articles', 'https://www.geeksforgeeks.org/']
Explanation:
- r'https?://\S+|www\.\S+' is a regex pattern to match URLs starting with http://, https://, or www.
- findall() extracts all matches in a list.
Using the urlparse()
urlparse() function from Python's urllib.parse module helps break down a URL into its key parts, such as the scheme (http, https), domain name, path, query parameters, and fragments. This function is useful for validating and extracting URLs from text by checking if a word follows a proper URL structure.
Python
from urllib.parse import urlparse
s = 'My Profile: https://auth.geeksforgeeks.org/user/Rayyyy%20/articles in the portal of https://www.geeksforgeeks.org/'
# Split the string into words
split_s = s.split()
# Empty list to collect URLs
urls = []
for word in split_s:
parsed = urlparse(word)
if parsed.scheme and parsed.netloc:
urls.append(word)
print("URLs:", urls)
OutputURLs: ['https://auth.geeksforgeeks.org/user/Rayyyy%20/articles', 'https://www.geeksforgeeks.org/']
Explanation:
- s.split() function splits the string to words.
- then urlparse(word) function checks each word to see if it has a valid scheme (http/https) and domain.
- URLs are added to url list using append() function.
Using urlextract()
urlextract is a third party library so to use it we need to first install it by giving the command "pip install urlextract" in out terminal, it offers a pre-built solution to find URLs in text. Its URLExtract class helps us to quickly identify URLs without needing custom patterns, making it a convenient choice for difficult extraction of URLs.
Python
from urlextract import URLExtract
s = 'My Profile: https://auth.geeksforgeeks.org/user/Prajjwal%20/articles in the portal of https://www.geeksforgeeks.org/'
extractor = URLExtract()
urls = extractor.find_urls(s)
print("URLs:", urls)
OutputUrls: ['https://auth.geeksforgeeks.org/user/Prajjwal%20/articles', 'https://www.geeksforgeeks.org/']
Explanation:
- import URLExtract from the urlextract library.
- URLExtract() creates an extractor object to scan the string.
- find_urls() detects all URLs in s and returns them as a list, no manual splitting or validation is needed.
Using startswith()
One simple approach is to split the string and check if each word starts with "https://" or "https://" using .startswith() built-in method, we can use .split() function to split the string and then check each word, if it starts with "https://" or "https://". If it does, we add it to our list of extracted URLs.
Python
s = 'My Profile: https://auth.geeksforgeeks.org/user/Rayyyy%20/articles in the portal of https://www.geeksforgeeks.org/'
x = s.split()
# Empty list to extract the URL
res=[]
for i in x:
if i.startswith("https:") or i.startswith("http:"):
res.append(i)
print("Urls: ", res)
OutputUrls: ['https://auth.geeksforgeeks.org/user/Rayyyy%20/articles', 'https://www.geeksforgeeks.org/']
Explanation:
- string.split() method splits the string into words.
- then we checks if each word starts with http:// or https:// using the "if" statement.
- if it does, then we add it to the list of URLs using .append() method.
Using find() method
find() is a built-in method in Python that is used to find a specific element in a collection, so we can use it to identify and extract a URL from a string. Here's how:
Python
s = 'My Profile: https://auth.geeksforgeeks.org/user/Rayyyy%20/articles in the portal of https://www.geeksforgeeks.org/'
split_s = s.split()
res=[]
for i in split_s:
if i.find("https:")==0 or i.find("http:")==0:
res.append(i)
print("Urls: ", res)
OutputUrls: ['https://auth.geeksforgeeks.org/user/Rayyyy%20/articles', 'https://www.geeksforgeeks.org/']
Explanation:
- s.split() funtion splits the string to words.
- identify url using i.find() function.
- add the URLs to the list 'res' using .append().
Related Articles:
Similar Reads
Python - Check if substring present in string The task is to check if a specific substring is present within a larger string. Python offers several methods to perform this check, from simple string methods to more advanced techniques. In this article, we'll explore these different methods to efficiently perform this check.Using in operatorThis
2 min read
Check if String Contains Substring in Python This article will cover how to check if a Python string contains another string or a substring in Python. Given two strings, check whether a substring is in the given string. Input: Substring = "geeks" String="geeks for geeks"Output: yesInput: Substring = "geek" String="geeks for geeks"Output: yesEx
8 min read
How to Urlencode a Querystring in Python? URL encoding a query string consists of converting characters into a format that can be safely transmitted over the internet. This process replaces special characters with a '%' followed by their hexadecimal equivalent. In this article, we will explore three different approaches to urlencode a query
2 min read
Requesting a URL from a local File in Python Making requests over the internet is a common operation performed by most automated web applications. Whether a web scraper or a visitor tracker, such operations are performed by any program that makes requests over the internet. In this article, you will learn how to request a URL from a local File
4 min read
How to check a valid regex string using Python? A Regex (Regular Expression) is a sequence of characters used for defining a pattern. This pattern could be used for searching, replacing and other operations. Regex is extensively utilized in applications that require input validation, Password validation, Pattern Recognition, search and replace ut
6 min read
How To Check Uuid Validity In Python? UUID (Universally Unique Identifier) is a 128-bit label used for information in computer systems. UUIDs are widely used in various applications and systems to uniquely identify information without requiring a central authority to manage the identifiers. This article will guide you through checking t
3 min read
Python | Sorting URL on basis of Top Level Domain Given a list of URL, the task is to sort the URL in the list based on the top-level domain. A top-level domain (TLD) is one of the domains at the highest level in the hierarchical Domain Name System of the Internet. Example - org, com, edu. This is mostly used in a case where we have to scrap the pa
3 min read
URL Shorteners and its API in Python | Set-2 Prerequisite: URL Shorteners and its API | Set-1 Let's discuss few more URL shorteners using the same pyshorteners module. Bitly URL Shortener: We have seen Bitly API implementation. Now let's see how this module can be used to shorten a URL using Bitly Services. Code to Shorten URL: Python3 1== fro
2 min read
URL Shorteners and its API in Python | Set-1 URL Shortener, as the name suggests, is a service to help to reduce the length of the URL so that it can be shared easily on platforms like Twitter, where number of characters is an issue. There are so many URL Shorteners available in the market today, that will definitely help you out to solve the
5 min read
Auto Search StackOverflow for Errors in Code using Python Ever faced great difficulty in copying the error you're stuck with, opening the browser, pasting it, and opening the right Stack Overflow Answer? Â Worry Not, Here's the solution! What we are going to do is to write a Python script, which automatically detects the error from code, search about it on
3 min read