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
Use urlparse to get just the path and then split the path you get from it on /
characters:
from urllib.parse import urlparse
my_url = "http://example.com/some/path/last?somequery=param"
last_path_fragment = urlparse(my_url).path.split('/')[-1] # returns 'last'
Note: if your url ends with a /
character, the above will return ''
(i.e. the empty string). If you want to handle that case differently, you need to strip the trailing /
character before you split the path:
my_url = "http://example.com/last/"
# handle URL ending in `/` by removing it.
last_path_fragment = urlparse(my_url).path.rstrip('/').split('/')[-1] # returns 'last'