Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if a URL is absolute using Python?

Tags:

python

What is the preferred solution for checking if an URL is relative or absolute?

like image 967
Geo Avatar asked Dec 02 '11 13:12

Geo


People also ask

How do you know if a URL is relative or absolute?

Original Answer. This will recognize an absolute URL, if: URL contains "://" anywhere after the first character, or. URL starts with "//" (protocol relative)

What is a valid absolute URL?

An absolute URL contains the entire address from the protocol (HTTPS) to the domain name (www.example.com) and includes the location within your website in your folder system (/foldernameA or /foldernameB) names within the URL.

How do I know if my path is absolute?

js, we can use the isAbsolute method from the path module. to check if myPath is an absolute path with path. isAbsolute . It should return true since it's an absolute path.

How do you create an absolute URL in Python?

Use abspath() to Get the Absolute Path in Python To get the absolute path using this module, call path. abspath() with the given path to get the absolute path. The output of the abspath() function will return a string value of the absolute path relative to the current working directory.


2 Answers

Python 2

You can use the urlparse module to parse an URL and then you can check if it's relative or absolute by checking whether it has the host name set.

>>> import urlparse >>> def is_absolute(url): ...     return bool(urlparse.urlparse(url).netloc) ...  >>> is_absolute('http://www.example.com/some/path') True >>> is_absolute('//www.example.com/some/path') True >>> is_absolute('/some/path') False 

Python 3

urlparse has been moved to urllib.parse, so use the following:

from urllib.parse import urlparse  def is_absolute(url):     return bool(urlparse(url).netloc) 
like image 91
Lukáš Lalinský Avatar answered Sep 21 '22 15:09

Lukáš Lalinský


If you want to know if an URL is absolute or relative in order to join it with a base URL, I usually do urllib.parse.urljoin anyway:

>>> from urllib.parse import urljoin >>> urljoin('http://example.com/', 'http://example.com/picture.png') 'http://example.com/picture.png' >>> urljoin('http://example1.com/', '/picture.png') 'http://example1.com/picture.png' >>>  
like image 44
warvariuc Avatar answered Sep 19 '22 15:09

warvariuc