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

前端 未结 6 984
南笙
南笙 2020-12-13 08:02

I decided that I\'ll learn python tonight :) I know C pretty well (wrote an OS in it) so I\'m not a noob in programming so everything in python seems pretty easy, but I don\

6条回答
  •  孤城傲影
    2020-12-13 08:39

    Thank you very much to the other answerers here, who pointed me in the right direction via the answers they have given!

    It seems like the posixpath module mentioned by sykora's answer is not available in my Python setup (python 2.7.3).

    As per this article it seems that the "proper" way to do this would be using...

    • urlparse.urlparse and urlparse.urlunparse can be used to detach and reattach the base of the URL
    • The functions of os.path can be used to manipulate the path
    • urllib.url2pathname and urllib.pathname2url (to make path name manipulation portable, so it can work on Windows and the like)

    So for example (not including reattaching the base URL)...

    >>> import urlparse, urllib, os.path
    >>> os.path.dirname(urllib.url2pathname(urlparse.urlparse("http://example.com/random/folder/path.html").path))
    '/random/folder'
    

提交回复
热议问题