如何获取 URL 中最后一个斜杠后的所有内容? [英] How to get everything after last slash in a URL?
本文介绍了如何获取 URL 中最后一个斜杠后的所有内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在 Python 中提取 URL 中最后一个斜杠后面的内容?例如,这些 URL 应返回以下内容:
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
我已经尝试过 urlparse,但这给了我完整的路径文件名,例如 page/page/12345
.
I've tried urlparse, but that gives me the full path filename, such as page/page/12345
.
推荐答案
不需要花哨的东西,看标准库中的字符串方法,您可以轻松地在文件名"部分和其余部分之间拆分您的网址:
You don't need fancy things, just see the string methods in the standard library and you can easily split your url between 'filename' part and the rest:
url.rsplit('/', 1)
这样您就可以简单地获得您感兴趣的部分:
So you can get the part you're interested in simply with:
url.rsplit('/', 1)[-1]
这篇关于如何获取 URL 中最后一个斜杠后的所有内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文