我有两个网址:
url1 = "http://127.0.0.1/test1/test2/test3/test5.xml"
url2 = "../../test4/test6.xml"
Run Code Online (Sandbox Code Playgroud)
如何获取url2的绝对URL?
Céd*_*ien 187
你应该使用urlparse.urljoin:
>>> import urlparse
>>> urlparse.urljoin(url1, url2)
'http://127.0.0.1/test1/test4/test6.xml'
Run Code Online (Sandbox Code Playgroud)
使用Python 3(其中urlparse被重命名为urllib.parse),您可以使用它如下:
>>> import urllib.parse
>>> urllib.parse.urljoin(url1, url2)
'http://127.0.0.1/test1/test4/test6.xml'
Run Code Online (Sandbox Code Playgroud)
rya*_*lon 15
您可以使用它reduce
以更干净的方式实现 Shikhar 的方法。
>>> import urllib.parse
>>> from functools import reduce
>>> reduce(urllib.parse.urljoin, ["http://moc.com/", "path1/", "path2/", "path3/"])
'http://moc.com/path1/path2/path3/'
Run Code Online (Sandbox Code Playgroud)
请注意,使用此方法,每个片段都应该有尾随正斜杠,没有前导正斜杠,以指示它是要连接的路径片段。
这是更正确/信息更丰富的,告诉您这path1/
是一个 URI 路径片段,而不是完整路径(例如/path1/
)或未知路径(例如path1
)。未知的可能是其中之一,但它们被作为完整路径处理。
如果您需要添加/
到缺少它的片段,您可以这样做:
uri = uri if uri.endswith("/") else f"{uri}/"
Run Code Online (Sandbox Code Playgroud)
要了解有关 URI 解析的更多信息,维基百科有一些很好的示例。
更新
刚刚注意到 Peter Perron 对 Shikhar 的答案评论了减少,但我将把它留在这里来演示这是如何完成的。
更新了维基百科 URL
对于 python 3.0+,加入 url 的正确方法是:
from urllib.parse import urljoin
urljoin('https://10.66.0.200/', '/api/org')
# output : 'https://10.66.0.200/api/org'
Run Code Online (Sandbox Code Playgroud)
小智 6
es = ['http://127.0.0.1', 'test1', 'test4', 'test6.xml']
base = ''
map(lambda e: urlparse.urljoin(base, e), es)
Run Code Online (Sandbox Code Playgroud)
>>> from urlparse import urljoin
>>> url1 = "http://www.youtube.com/user/khanacademy"
>>> url2 = "/user/khanacademy"
>>> urljoin(url1, url2)
'http://www.youtube.com/user/khanacademy'
Run Code Online (Sandbox Code Playgroud)
简单的。
如果您的相对路径由多个部分组成,则您必须将它们分别连接起来,因为urljoin
它将替换相对路径,而不是将其合并。最简单的方法是使用posixpath
。
>>> import urllib.parse
>>> import posixpath
>>> url1 = "http://127.0.0.1"
>>> url2 = "test1"
>>> url3 = "test2"
>>> url4 = "test3"
>>> url5 = "test5.xml"
>>> url_path = posixpath.join(url2, url3, url4, url5)
>>> urllib.parse.urljoin(url1, url_path)
'http://127.0.0.1/test1/test2/test3/test5.xml'
Run Code Online (Sandbox Code Playgroud)