Check if an URL is valid or not with Python

Configurare noua (How To)

Situatie

Given a URL as a character string str of size N.The task is to check if the given URL is valid or not.

Backup

Input : str = “https://www.youtube.com/”
Output : Yes
Explanation :
The above URL is a valid URL.
Input : str = “https:// www.youtube.com/”
Output : No
Explanation :
Note that there is a space after https://, hence the URL is invalid.

Solutie

import re
# Function to validate URL
# using regular expression
def isValidURL(str):
    # Regex to check valid URL
    regex = ("((http|https)://)(www.)?" +
             "[a-zA-Z0-9@:%._\\+~#?&//=]" +
             "{2,256}\\.[a-z]" +
             "{2,6}\\b([-a-zA-Z0-9@:%" +
             "._\\+~#?&//=]*)")
    
    # Compile the ReGex
    p = re.compile(regex)
    # If the string is empty
    # return false
    if (str == None):
        return False
    # Return if the string
    # matched the ReGex
    if(re.search(p, str)):
        return True
    else:
        return False
# Driver code
# Test Case 1:
url = "https://www.youtube.com"
if(isValidURL(url) == True):
    print("Yes")
else:
    print("No")
Output:

Yes

Tip solutie

Permanent

Voteaza

(9 din 19 persoane apreciaza acest articol)

Despre Autor

Leave A Comment?