我有来自用户的url
,我必须用获取的HTML进行回复。
如何检查URL是否格式错误?
例如:
url = 'google' # Malformed
url = 'google.com' # Malformed
url = 'http://google.com' # Valid
url = 'http://google' # Malformed
发布于 2011-08-23 20:06:48
django url验证正则表达式(source):
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
发布于 2015-08-24 05:46:02
使用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
>>>
使用pip (pip install validators
)将其安装为from PyPI。
发布于 2011-08-23 20:10:17
实际上,我认为这是最好的方法。
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
,它将实际验证该URL是否存在,否则它将只检查其格式是否正确。
编辑:啊,是的,这个问题是这个的副本:How can I check if a URL exists with Django’s validators?
https://stackoverflow.com/questions/7160737
复制相似问题