将URL路径拆分为组件

时间:2017-01-04 18:56:02

标签: python url parameters split components

根据网址http://www.example.com/users/john-doe/detail,如何创建此表单['/users', '/users/john-doe', '/users/john-doe/detail']的列表?

1 个答案:

答案 0 :(得分:5)

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

>>> 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']