如何在Python中验证网址?(是否格式正确)

229 投票
17 回答
332766 浏览
提问于 2025-04-17 00:11

我有一个用户提供的url,我需要返回获取到的HTML内容。

我该如何检查这个URL是否格式正确呢?

比如说:

url = 'google' # Malformed
url = 'google.com' # Malformed
url = 'http://google.com' # Valid
url = 'http://google' # Malformed

17 个回答

154

其实,我觉得这是最好的方法。

from django.core.validators import URLValidator
from django.core.exceptions import ValidationError

val = URLValidator(verify_exists=False)
try:
    val('http://www.google.com')
except ValidationError, e:
    print e

如果你把 verify_exists 设置为 True,它会真的去验证这个网址是否存在,否则它只会检查这个网址的格式是否正确。

补充一下:哦,对了,这个问题其实是重复的,相关链接在这里: 我该如何用Django的验证器检查一个网址是否存在?

233

使用 validators 这个包:

>>> import validators
>>> validators.url("http://google.com")
True
>>> validators.url("http://google")
ValidationFailure(func=url, args={'value': 'http://google', 'require_tld': True})
>>> if not validators.url("http://google"):
...     print "not valid"
... 
not valid
>>>

你可以通过 PyPI 来安装它,使用 pip 命令(pip install validators)。

135

Django URL 验证的正则表达式 (来源):

import re
regex = re.compile(
        r'^(?:http|ftp)s?://' # http:// or https://
        r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' #domain...
        r'localhost|' #localhost...
        r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
        r'(?::\d+)?' # optional port
        r'(?:/?|[/?]\S+)$', re.IGNORECASE)

print(re.match(regex, "http://www.example.com") is not None) # True
print(re.match(regex, "example.com") is not None)            # False

撰写回答