如何在 Python 中验证 url?(畸形与否) [英] How to validate a url in Python? (Malformed or not)
本文介绍了如何在 Python 中验证 url?(畸形与否)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有来自用户的 url
,我必须用获取的 HTML 回复.
I have url
from the user and I have to reply with the fetched HTML.
如何检查 URL 是否格式错误?
How can I check for the URL to be malformed or not?
例如:
url = 'google' # Malformed
url = 'google.com' # Malformed
url = 'http://google.com' # Valid
url = 'http://google' # Malformed
推荐答案
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
这篇关于如何在 Python 中验证 url?(畸形与否)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文