You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中按斜杠分隔URL并保留分隔符生成子端点

Python生成URL的所有子端点

直接用split('/')确实会因为URL的协议前缀(比如https://)导致拆分混乱,推荐用Python标准库urllib.parse来解析URL结构,避免手动处理的漏洞,以下是具体实现:

单个URL处理函数

这个函数可以把输入的URL拆解为所有层级的子端点,完全匹配你要的输出格式:

import urllib.parse

def generate_sub_endpoints(url):
    # 解析URL,拆分协议、域名、路径等部分
    parsed_url = urllib.parse.urlsplit(url)
    # 拆分路径段,过滤空字符串(处理路径首尾的/)
    path_segments = [seg for seg in parsed_url.path.split('/') if seg]
    
    sub_endpoints = []
    current_path = ""
    
    for idx, segment in enumerate(path_segments):
        current_path += f"/{segment}"
        # 拼接子端点:前几个子路径结尾加/,最后一个完整路径不加
        if idx != len(path_segments) - 1:
            full_endpoint = urllib.parse.urlunsplit(
                (parsed_url.scheme, parsed_url.netloc, current_path + "/", "", "")
            )
        else:
            full_endpoint = urllib.parse.urlunsplit(
                (parsed_url.scheme, parsed_url.netloc, current_path, "", "")
            )
        sub_endpoints.append(full_endpoint)
    
    return sub_endpoints

测试示例

test_url = "https://www.somesite.com/path1/path2/path3"
result = generate_sub_endpoints(test_url)
for item in result:
    print(item)

输出结果:

https://www.somesite.com/path1/
https://www.somesite.com/path1/path2/
https://www.somesite.com/path1/path2/path3

处理URL列表文件

如果要批量处理文件中的URL列表,比如读取urls.txt(每行一个URL),并输出所有子端点:

with open("urls.txt", "r") as input_file:
    for line in input_file:
        url = line.strip()
        if not url:
            continue  # 跳过空行
        endpoints = generate_sub_endpoints(url)
        # 打印结果,也可以写入到输出文件
        print("\n".join(endpoints))
        # 写入文件的话取消下面注释
        # with open("sub_endpoints.txt", "a") as output_file:
        #     output_file.write("\n".join(endpoints) + "\n")

为什么不用直接split

直接用split('/')会把https://拆成['https:', '', 'www.somesite.com', ...],需要额外处理这些无效段,而urllib.parse是专门为URL解析设计的工具,能兼容各种合法URL(比如带端口https://example.com:8080/path、带子域名的情况),更稳定可靠。

内容的提问来源于stack exchange,提问作者FozenOption

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 21:50:40