How to check if a URL is valid in Python?
Published on Aug. 22, 2023, 12:18 p.m.
In Python, you can use the urllib.parse
module to check if a URL is valid. Specifically, you can use the urlparse()
function to parse the URL and check if its components are valid. Here is an example:
from urllib.parse import urlparse
def is_valid_url(url):
try:
result = urlparse(url)
return all([result.scheme, result.netloc])
except:
return False
This function takes a URL as an argument and returns True
if the URL is valid, and False
otherwise. It first uses urlparse()
to parse the URL into its components, such as scheme, netloc, etc. Then, it checks if both the scheme and netloc components are present, since those are the two required components for a valid URL. If either of those components is missing, the function returns False
.
Note that this function does not actually check if the URL is reachable or if it returns valid content - it only checks the format of the URL itself.