Python: Get URL path sections

后端 未结 7 1627
长发绾君心
长发绾君心 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:38

    Python 3.4+ solution:

    from urllib.parse import unquote, urlparse
    from pathlib import PurePosixPath
    
    url = 'http://www.example.com/hithere/something/else'
    
    PurePosixPath(
        unquote(
            urlparse(
                url
            ).path
        )
    ).parts[1]
    
    # returns 'hithere' (the same for the URL with parameters)
    
    # parts holds ('/', 'hithere', 'something', 'else')
    #               0    1          2            3
    
    

提交回复
热议问题