Saturday, August 15, 2009

How to decode a URL using python

I was doing a task and i needed a function to decoded a url as a dictionary of parameters and its values,

since i used urllib.urlencode before i was sure that i will find urllib.decode method as well, but i didn't.

Here is the result of my search, to decode a url into dictionary of parameter and its values user the cgi module as the follwoing:



import cgi

import urllib

url = 'http://www.test.com/test?%s'

params = {'param1': 'value1', 'param2': 'value2'}

urlParams = urllib.urlencode(params)

url = url%urlParams

resultParams = dict(cgi.parse_qsl(url))

print result_params



Enjoy

No comments: