pythonurlparsescene7

how do i replace a query with a new value in urlparse?


so I have a data as follows:

 item = '//s780.scene7.com/is/image/forever/301596014_001?hei=98&wid=98'

using urlparse module. how can i replace the above data with a new size to make it look like this:

  item = '//s780.scene7.com/is/image/forever/301596014_001?hei=360&wid=360'

Solution

  • Here is an answer which, as requested, uses urlparse:

    import urllib
    import urlparse
    
    url = '//s780.scene7.com/is/image/forever/301596014_001?hei=98&wid=98'
    parts = urlparse.urlparse(url)
    query_dict = urlparse.parse_qs(parts.query)  # {'wid': ['98'], 'hei': ['98']}
    query_dict['wid'] = '360'
    query_dict['hei'] = '360'
    new_parts = list(parts)
    new_parts[4] = urllib.urlencode(query_dict)
    print urlparse.urlunparse(new_parts)