Resolving a relative url path to its absolute path

前端 未结 2 1091
南方客
南方客 2020-12-23 15:58

Is there a library in python that works like this?

>>> resolvePath(\"http://www.asite.com/folder/currentpage.html\", \"anotherpage.html\")
\'http://         


        
2条回答
  •  南笙
    南笙 (楼主)
    2020-12-23 16:44

    Yes, there is urlparse.urljoin, or urllib.parse.urljoin for Python 3.

    >>> 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'
    

    for copy-and-paste:

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

提交回复
热议问题