Python: Get URL path sections

后端 未结 7 1596
长发绾君心
长发绾君心 2020-12-01 05:15

How do I get specific path sections from a url? For example, I want a function which operates on this:

http://www.mydomain.com/hithere?image=2934

相关标签:
7条回答
  • 2020-12-01 05:59

    Extract the path component of the URL with urlparse:

    >>> import urlparse
    >>> path = urlparse.urlparse('http://www.example.com/hithere/something/else').path
    >>> path
    '/hithere/something/else'
    

    Split the path into components with os.path.split:

    >>> import os.path
    >>> os.path.split(path)
    ('/hithere/something', 'else')
    

    The dirname and basename functions give you the two pieces of the split; perhaps use dirname in a while loop:

    >>> while os.path.dirname(path) != '/':
    ...     path = os.path.dirname(path)
    ... 
    >>> path
    '/hithere'
    
    0 讨论(0)
提交回复
热议问题