将URL路径拆分为组件

sas*_*cha 2 python parameters url components split

给定一个URL http://www.example.com/users/john-doe/detail,我该如何创建这个表单的列表['/users', '/users/john-doe', '/users/john-doe/detail']

ale*_*cxe 5

您可以使用urlparse获取URL 路径,然后拆分部分并构造路径变体:

>>> from urllib.parse import urlparse  # Python 3.x
>>>
>>> url = "http://www.example.com/users/john-doe/detail"
>>> urlparse(url)
>>>
>>> path = urlparse(url).path[1:]
>>> parts = path.split('/')
>>> ['/' + '/'.join(parts[:index+1]) for index in range(len(parts))]
['/users', '/users/john-doe', '/users/john-doe/detail']
Run Code Online (Sandbox Code Playgroud)