code_junkie

How can I split a url string up into separate parts in Python

Nov 13th, 2011
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.05 KB | None | 0 0
  1. >>> from urllib.parse import urlparse
  2. >>> url = 'http://example.com/random/folder/path.html'
  3. >>> parse_object = urlparse(url)
  4. >>> parse_object.netloc
  5. 'example.com'
  6. >>> parse_object.path
  7. '/random/folder/path.html'
  8. >>> parse_object.scheme
  9. 'http'
  10. >>>
  11.  
  12. >>> from posixpath import basename, dirname
  13. >>> basename(parse_object.path)
  14. 'path.html'
  15. >>> dirname(parse_object.path)
  16. '/random/folder'
  17.  
  18. >>> URL = "http://example.com/random/folder/path.html"
  19. >>> Segments = URL.rpartition('/')
  20. >>> Segments[0]
  21. 'http://example.com/random/folder'
  22. >>> Segments[2]
  23. 'path.html'
  24.  
  25. (everything to the left of char , the character itself , everything to the right of char)
  26.  
  27. url = 'http://example.com/random/folder/path.html'
  28. # Create a list of each bit between slashes
  29. slashparts = url.split('/')
  30. # Now join back the first three sections 'http:', '' and 'example.com'
  31. basename = '/'.join(slashparts[:3]) + '/'
  32. # All except the last one
  33. dirname = '/'.join(slashparts[:-1]) + '/'
  34. print 'slashparts = %s' % slashparts
  35. print 'basename = %s' % basename
  36. print 'dirname = %s' % dirname
  37.  
  38. split
Add Comment
Please, Sign In to add comment