How to join absolute and relative urls?

后端 未结 6 1470
谎友^
谎友^ 2020-12-02 12:07

I have two urls:

url1 = \"http://127.0.0.1/test1/test2/test3/test5.xml\"
url2 = \"../../test4/test6.xml\"

How can I get an absolute url for

6条回答
  •  有刺的猬
    2020-12-02 12:21

    If your relative path consists of multiple parts, you have to join them separately, since urljoin would replace the relative path, not join it. The easiest way to do that is to use 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'
    

    See also: How to join components of a path when you are constructing a URL in Python

提交回复
热议问题