How to get everything after last slash in a URL?

后端 未结 12 2206
心在旅途
心在旅途 2020-12-02 08:26

How can I extract whatever follows the last slash in a URL in Python? For example, these URLs should return the following:

URL: http://www.test.com/TEST1
ret         


        
12条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-02 08:45

    First extract the path element from the URL:

    from urllib.parse import urlparse
    parsed= urlparse('https://www.dummy.example/this/is/PATH?q=/a/b&r=5#asx')
    

    and then you can extract the last segment with string functions:

    parsed.path.rpartition('/')[2]
    

    (example resulting to 'PATH')

提交回复
热议问题