我正在嘗試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 urlparsedef 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
添加回答
舉報
0/150
提交
取消