如何用Python检查URL是否为绝对路径?

44 投票
4 回答
19629 浏览
提问于 2025-04-17 07:32

检查一个网址是相对地址还是绝对地址,最好的方法是什么呢?

4 个回答

3

因为不能对已接受的答案评论,所以我把这个评论写成新的答案:我认为在已接受的答案中检查方案(bool(urlparse.urlparse(url).scheme))并不是一个好主意,因为像http://example.com/file.jpghttps://example.com/file.jpg和//example.com/file.jpg这些都是绝对网址,但在最后一种情况下,我们得到的方案却是空的(scheme = '')。

我使用的代码是:

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

31

如果你想知道一个网址是绝对地址还是相对地址,以便把它和一个基础网址结合起来,我通常会使用 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'
>>> 
72

Python 2

你可以使用 urlparse 这个模块来解析一个网址,然后你可以通过检查它是否有主机名来判断这个网址是相对的还是绝对的。

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

撰写回答