Resolving a relative url path to its absolute path

PythonUrlPath

Python Problem Overview


Is there a library in python that works like this?

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

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

You can also call the urljoin function through Python's requests library.

This code:

import requests

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

Will return a value of http://example.com/bar.html

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEric Palakovich CarrView Question on Stackoverflow
Solution 1 - PythonJames BradyView Answer on Stackoverflow
Solution 2 - PythonPikamander2View Answer on Stackoverflow