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

前端 未结 4 1063
旧时难觅i
旧时难觅i 2020-12-10 10:20

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

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-10 10:42

    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)
    

提交回复
热议问题