How can I get the base of a URL in Python?

前端 未结 8 2479
情书的邮戳
情书的邮戳 2021-02-12 12:34

I\'m trying to determine the base of a URL, or everything besides the page and parameters. I tried using split, but is there a better way than splitting it up into pieces? Is th

8条回答
  •  渐次进展
    2021-02-12 12:59

    There is shortest solution for Python3 with use of urllib library (don't know if fastest):

    from urllib.parse import urljoin
    
    base_url = urljoin('http://127.0.0.1/asdf/login.php', '.')
    # output: http://127.0.0.1/asdf/
    

    Keep in mind that urllib library supports uri/url compatible with HTML's keyword. It means that uri/url ending with '/' means different that without like here https://stackoverflow.com/a/1793282/7750840/:

    base_url = urljoin('http://127.0.0.1/asdf/', '.')
    # output: http://127.0.0.1/asdf/
    
    base_url = urljoin('http://127.0.0.1/asdf', '.')
    # output: http://127.0.0.1/
    

    This is link to urllib for python: https://pythonprogramming.net/urllib-tutorial-python-3/

提交回复
热议问题