如何使用Python检查URL是否为绝对值?



检查URL是相对的还是绝对的首选解决方案是什么?

Python 2

您可以使用urlparse模块解析URL,然后您可以通过检查它是否设置了主机名来检查它是相对的还是绝对的。

>>> 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已被移至urllib.parse,因此使用以下命令:

from urllib.parse import urlparse
def is_absolute(url):
    return bool(urlparse(url).netloc)

如果您想知道URL是绝对的还是相对的,以便与基础URL连接,我通常做urllib.parse.urljoin:

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

不能评论接受的答案,所以把这个评论写为新的答案:IMO在接受的答案(bool(urlparse.urlparse(url).scheme))中检查方案不是一个好主意,因为http://example.com/file.jpg, https://example.com/file.jpg和//example.com/file.jpg是绝对url,但在最后一种情况下,我们得到scheme ="

我使用以下代码:

is_absolute = True if '//' in my_url else False

最新更新