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

时间:2009-01-24 19:10:00

标签: python url path

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 个答案:

答案 0 :(得分:97)

是的,Python 3有urlparse.urljoinurllib.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

答案 1 :(得分:1)

您还可以通过Python的urljoin库调用requests函数。

此代码:

import requests

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

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