Python:如何解析包含".."的URL

Nic*_*rdu 8 python url

我需要唯一标识和存储一些URL.问题是,有时它们会包含"......" http://somedomain.com/foo/bar/../../some/url,http://somedomain.com/some/url如果我没有错,基本上就是这样.

是否有Python函数或解决此URL的棘手方法?

Jos*_*Lee 12

使用urlparse有一个简单的解决方案 .urljoin:

>>> import urlparse
>>> urlparse.urljoin('http://www.example.com/foo/bar/../../baz/bux/', '.')
'http://www.example.com/baz/bux/'
Run Code Online (Sandbox Code Playgroud)

但是,如果没有尾部斜杠(最后一个组件是文件,而不是目录),则将删除最后一个组件.

此修复程序使用urlparse函数提取路径,然后使用(posixpath版本)os.path来规范化组件.使用尾部斜杠补偿一个神秘的问题,然后将URL重新加入.以下是doctest:

import urlparse
import posixpath

def resolveComponents(url):
    """
    >>> resolveComponents('http://www.example.com/foo/bar/../../baz/bux/')
    'http://www.example.com/baz/bux/'
    >>> resolveComponents('http://www.example.com/some/path/../file.ext')
    'http://www.example.com/some/file.ext'
    """

    parsed = urlparse.urlparse(url)
    new_path = posixpath.normpath(parsed.path)
    if parsed.path.endswith('/'):
        # Compensate for issue1707768
        new_path += '/'
    cleaned = parsed._replace(path=new_path)
    return cleaned.geturl()
Run Code Online (Sandbox Code Playgroud)