python解析url
1 url = "https://www.baidu.com/a/b/c/?q=d&q=e&q=f" 2 3 # 1. 先找到协议和域名 4 # 以 "://" 分割 5 protocol_end_index = url.find("://") 6 if protocol_end_index != -1: 7 protocol = url[:protocol_end_index] 8 rest = url[protocol_end_index + 3:] 9 else: 10 protocol = '' 11 rest = url 12 13 # 2. 分离域名和路径+查询 14 # 找第一个 "/" 来区分域名和路径 15 # domain, pathquery = rest.split("/", 1) 16 # print(domain) 17 18 slash_index = rest.find("/") 19 20 if slash_index != -1: 21 domain = rest[:slash_index] 22 path_query = rest[slash_index:] 23 else: 24 domain = rest 25 path_query = '' 26 27 # 3. 分离路径和查询参数 28 question_mark_index = path_query.find("?") 29 if question_mark_index != -1: 30 path = path_query[:question_mark_index] 31 query_str = path_query[question_mark_index + 1:] 32 else: 33 path = path_query 34 query_str = '' 35 36 37 # 4. 解析查询参数(可能有多个相同的键) 38 query_params = {} 39 if query_str: 40 pairs = query_str.split("&") 41 for pair in pairs: 42 if "=" in pair: 43 key, value = pair.split("=", 1) 44 if key in query_params: 45 query_params[key].append(value) 46 else: 47 query_params[key] = [value] 48 else: 49 # 没有 "=" 的情况 50 query_params[pair] = [] 51 52 # 输出解析结果 53 print("协议:", protocol) 54 print("域名:", domain) 55 print("路径:", path) 56 print("查询参数:", query_params)
结果:
协议: https 域名: www.baidu.com 路径: /a/b/c/ 查询参数: {'q': ['d', 'e', 'f']}

浙公网安备 33010602011771号