将相对URL路径解析为绝对路径

77

Python中是否有类似这样的库?

>>> resolvePath("http://www.asite.com/folder/currentpage.html", "anotherpage.html")
'http://www.asite.com/folder/anotherpage.html'
>>> resolvePath("http://www.asite.com/folder/currentpage.html", "folder2/anotherpage.html")
'http://www.asite.com/folder/folder2/anotherpage.html'
>>> resolvePath("http://www.asite.com/folder/currentpage.html", "/folder3/anotherpage.html")
'http://www.asite.com/folder3/anotherpage.html'
>>> resolvePath("http://www.asite.com/folder/currentpage.html", "../finalpage.html")
'http://www.asite.com/finalpage.html'
2个回答

127

是的,有 urlparse.urljoin, 或者 Python 3 中的 urllib.parse.urljoin

>>> try: from urlparse import urljoin # Python2
... except ImportError: from urllib.parse import urljoin # Python3
...
>>> urljoin("http://www.asite.com/folder/currentpage.html", "anotherpage.html")
'http://www.asite.com/folder/anotherpage.html'
>>> urljoin("http://www.asite.com/folder/currentpage.html", "folder2/anotherpage.html")
'http://www.asite.com/folder/folder2/anotherpage.html'
>>> urljoin("http://www.asite.com/folder/currentpage.html", "/folder3/anotherpage.html")
'http://www.asite.com/folder3/anotherpage.html'
>>> urljoin("http://www.asite.com/folder/currentpage.html", "../finalpage.html")
'http://www.asite.com/finalpage.html'

可直接复制粘贴使用:

try:
    from urlparse import urljoin  # Python2
except ImportError:
    from urllib.parse import urljoin  # Python3

如需符合RFC 3986和Unicode标准的替代方案,请参阅uritools - Marian
1
遗憾的是,如果第二个组件是绝对路径,则此方法无法正常工作。例如,urljoin("http://example.com/blah.html", "./././whoa.html")会删除点,而 urljoin("http://example.com/blah.html", "/./././whoa.html")则不会。 - obskyr
2
请注意,这仅限于一组硬编码的方案。如果您使用自定义/不受欢迎的方案,则需要修改urllib.parse.uses_relativeurllib.parse.uses_netloc以包括您的方案,如果您想使其工作。关于全局状态方面不太美观,但我没有看到其他方法可以在不修补标准库的情况下完成此操作。 - user8866053
@obskyr 这是有效的。它的行为与RFC 1808第4节定义的算法相同。因此,它是“正确的”。在RFC1808中,将相对路径而不是绝对路径的“.”部分折叠起来是一种奇特的方式,但这是解释此类URL的标准方式。 - Philip Couling

14
你也可以通过Python的requests库调用urljoin函数。
这段代码:
import requests

requests.compat.urljoin('http://example.com/foo.html', 'bar.html')

将返回值http://example.com/bar.html


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接