Convert relative url to full url using Python

I am looking for a way to fully determine the URL using Python. I have the current page URL, for example:

http://www.foo.com/Stuff/Mike/Doc.html

and I have my href, for example:

href = "../Bob/doc.html"

I need to build:

http://www.foo.com/Stuff/Bob/Doc.html

Are there any libraries in Python that can parse such paths? I looked through the docs for urllib and urllib2, but couldn't find anything like it. Thank!

+5
source share
2 answers

Use the library urlparse.

>>> import urlparse
>>> urlparse.urljoin("http://www.foo.com/Stuff/Mike/Doc.html","../Bob/Doc.html")
'http://www.foo.com/Stuff/Bob/Doc.html'
+7
source

Additionally:

python 3, :

>>> from urllib.parse import urljoin
>>> urlparse.urljoin("http://www.foo.com/Stuff/Mike/Doc.html","../Bob/Doc.html")
'http://www.foo.com/Stuff/Bob/Doc.html'
+1

All Articles