如果需要,可以使用urlparse(例如,摆脱任何查询字符串参数)。
import urllib.parse
urls = [
'http://www.test.com/TEST1',
'http://www.test.com/page/TEST2',
'http://www.test.com/page/page/12345',
'http://www.test.com/page/page/12345?abc=123'
]
for i in urls:
url_parts = urllib.parse.urlparse(i)
path_parts = url_parts[2].rpartition('/')
print('URL: {}\nreturns: {}\n'.format(i, path_parts[2]))
输出:
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
URL: http://www.test.com/page/page/12345?abc=123
returns: 12345
...?foo=bar
而您不希望这样做;我建议urlparse
与naeg的建议结合使用basename
。