python解析url,返回协议、域名、主机、端口号、资源等(类似 JavaScript 中的location对象) 作者:马育民 • 2025-01-27 21:34 • 阅读:10016 ``` def parse_url(url): ''' 分析url,获取以下信息: { 'protocol': 'https:', 协议 'host': 'localhost:8080', 主机和端口 'hostname': 'localhost', 主机 'port': '8080', 端口 'pathname': '/videos/fsdss-005/' 资源 'search': '' ? 后面的参数 'hash': '' #后面的部分 } 不是有效的 HTTP 或 HTTPS 格式,返回None ''' url_temp = '' pos = url.find(":") if pos < 0: # raise Exception ("不是有效的 HTTP 或 HTTPS 格式,无法解析!") return None protocol = url[:pos+1] leng = len(protocol+"//") # http:// 或 https:// 长度 # print("leng:",leng) pos2 = url.find("/",leng + 1) # 域名后面的 / 位置 if pos2 >= 0: host = url[ leng : pos2 ] url_temp = url[pos2:] # 域名后面的部分,开头有 / # print("url_temp::",url_temp) else: host = url[leng:] host_arr = host.split(":") hostname = host_arr[0] port = 80 if len(host_arr) == 2: port = int(host_arr[1]) wen_pos = url_temp.find("?") # 问号位置 jing_pos = url_temp.find("#") # #的位置 # 从后往前截取 # 截取出 #后面的部分 hash = '' if jing_pos >= 0: # #号存在 hash = url_temp[jing_pos :] # 新url,不包含#后面的部分 url_temp = url_temp[:jing_pos] # 截取出 ? 后面的参数 search = '' if wen_pos >= 0: search = url_temp[wen_pos : ] # 新url,不包含?、#后面的部分 url_temp = url_temp[:wen_pos] # 截取出资源 pathname = url_temp ret = { "protocol":protocol, "host":host, "hostname":hostname, "port":port, "pathname":pathname, "search":search, "hash":hash, } return ret ``` ``` location = parse_url("http://www.example.com:8080/test.php?user=admin&pwd=admin#login") print(locaiton) ``` 执行结果: ``` { 'protocol': 'http:', 'host': 'www.example.com:8080', 'hostname': 'www.example.com', 'port': '8080', 'pathname': '/test.php', 'search': '?user=admin&pwd=admin', 'hash': '#login' } ``` 测试: ``` res = parse_url("http://www.example.com") print(res) res = parse_url("http://www.example.com:8080") print(res) res = parse_url("http://www.example.com:8080/test.php?user=admin&pwd=admin#login") print(res) res = parse_url("https://dot-lobo.mushroomtrack.com/hls/ihmScQTlvxjUOdu2zhCmXA/1738060868/4000/4889/48890.ts") print(res) res = parse_url("https://dot-lobo.mushroomtrack.com/hls/ihmScQTlvxjUOdu2zhCmXA/1738060868/4000/4889/48890.ts?name=lilei") print(res) res = parse_url("dot-lobo.mushroomtrack.com/hls/ihmScQTlvxjUOdu2zhCmXA/1738060868/4000/4889/48890.ts?name=lilei") print(res) res = parse_url("https://dot-lobo.mushroomtrack.com/hls/ihmScQTlvxjUOdu2zhCmXA/1738060868/4000/4889/48890.ts#哈哈") print(res) ``` 原文出处:https://malaoshi.top/show_1GWU4Y7srVH.html