python how to check if url is valid code example
Example 1: python validate url
django url validation regex (source):
import re
regex = re.compile(
r'^(?:http|ftp)s?://'
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|'
r'localhost|'
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'
r'(?::\d+)?'
r'(?:/?|[/?]\S+)$', re.IGNORECASE)
print(re.match(regex, "http://www.example.com") is not None)
print(re.match(regex, "example.com") is not None)
Example 2: python check if string is url
from django.core.validators import URLValidator()
validate = URLValidator()
try:
validate("http://www.avalidurl.com/")
print("String is a valid URL")
except ValidationError as exception:
print("String is not valid URL")