What is the preferred solution for checking if an 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)
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.
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.
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.
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
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)
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' >>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With