[Python] change urlparse.path of a url

Discussão em 'Python' iniciado por Stack, Julho 7, 2025.

  1. Stack

    Stack Membro Participativo

    Here is the python code:

    url = http://www.phonebook.com.pk/dynamic/search.aspx
    path = urlparse(url)
    print (path)

    >>>ParseResult(scheme='http', netloc='www.phonebook.com.pk', path='/dynamic/search.aspx', params='', query='searchtype=cat&class_id=4520&page=1', fragment='')

    print (path.path)
    >>>/dynamic/search.aspx


    Now I need to change the path.path to my requirement. Like if "/dynamic/search.aspx" is the path then I only need the parts between the first slash and last slash including slashes which is "/dynamic/".

    I have tried these two lines but end result is not what I expected that's why I am asking this question as my knowledge of "urllib.parse" is insufficient.

    path = path.path[:path.path.index("/")]
    print (path)
    >>>Returns nothing.
    path = path.path[path.path.index("/"):]
    >>>/dynamic/search.aspx (as it was before, no change.)


    In short whatever the path.path result is my need is directory names only. For example:" dynamic/search/search.aspx". now I need "dynamic/search/"

    Continue reading...

Compartilhe esta Página