我正在尝试1-65535
使用urlparse
.
棘手的部分是,如果 URL 中没有端口号,urlparse(url).port
则标识为NoneType
因此,我尝试根据数据类型进行简单的比较,但并没有像您在此示例中看到的那样真正起作用。
如果我NoneType
用作数据类型,
elif type(u.port) == NoneType:
我收到错误
NameError: name 'NoneType' is not defined
我没有使用,validators
因为它无法正确验证端口号。
TCP/UDP 端口号范围从 1-65535 开始。但是,validators
无法识别端口1-9
并且仍然接受大于65535
.
代码
from urllib.parse import urlparse
def test(url):
global u
u = urlparse(url)
print(' Port : ', u.port)
print(' Data Type : u.port %s\n'% type(u.port))
for url in ['example.com', 'example.com:1', 'http://example.com:1']:
print(url)
test(url)
if type(u.port) == int:
print(' Integer')
elif type(u.port) == None:
print(' None')
# elif type(u.port) == NoneType: # NameError: name 'NoneType' is not defined
# print(' None')
输出
example.com
Port : None
Data Type : u.port <class 'NoneType'>
example.com:1
Port : None
Data Type : u.port <class 'NoneType'>
http://example.com:1
Port : 1
Data Type : u.port <class 'int'>
Integer
守候你守候我
尚方宝剑之说
相关分类