How to get everything after last slash in a URL?

2019-01-21 07:25发布

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
returns: TEST1

URL: http://www.test.com/page/TEST2
returns: TEST2

URL: http://www.test.com/page/page/12345
returns: 12345

I've tried urlparse, but that gives me the full path filename, such as page/page/12345.

11条回答
SAY GOODBYE
2楼-- · 2019-01-21 07:46

Here's a more general, regex way of doing this:

    re.sub(r'^.+/([^/]+)$', r'\1', url)
查看更多
Viruses.
3楼-- · 2019-01-21 07:48
os.path.basename(os.path.normpath('/folderA/folderB/folderC/folderD/'))

folderD

查看更多
疯言疯语
4楼-- · 2019-01-21 07:50

One more (idio(ma)tic) way:

URL.split("/")[-1]
查看更多
爷的心禁止访问
5楼-- · 2019-01-21 07:55

rsplit should be up to the task:

In [1]: 'http://www.test.com/page/TEST2'.rsplit('/', 1)[1]
Out[1]: 'TEST2'
查看更多
Ridiculous、
6楼-- · 2019-01-21 07:55

Split the url and pop the last element url.split('/').pop()

查看更多
爷、活的狠高调
7楼-- · 2019-01-21 07:56
extracted_url = url[url.rfind("/")+1:];
查看更多
登录 后发表回答