Retrieving parameters from a URL

Posted on

Question :

Retrieving parameters from a URL

Given a URL like the following, how can I parse the value of the query parameters? For example, in this case I want the value of def.


I am using Django in my environment; is there a method on the request object that could help me?

I tried using self.request.get('def') but it is not returning the value ghi as I had hoped.

Asked By: niteshb


Answer #1:

Python 2:

import urlparse
url = ''
parsed = urlparse.urlparse(url)
print urlparse.parse_qs(parsed.query)['def']

Python 3:

import urllib.parse as urlparse
from urllib.parse import parse_qs
url = ''
parsed = urlparse.urlparse(url)

parse_qs returns a list of values, so the above code will print ['ghi'].

Here’s the Python 3 documentation.

Answered By: systempuntoout

Answer #2:

I’m shocked this solution isn’t on here already. Use:


This will “get” the variable from the “GET” dictionary, and return the ‘variable_name’ value if it exists, or a None object if it doesn’t exist.

Answered By: jball037

Answer #3:

import urlparse
url = ''
par = urlparse.parse_qs(urlparse.urlparse(url).query)

print par['q'][0], par['p'][0]
Answered By: Cris

Answer #4:

for Python > 3.4

from urllib import parse
url = ''
Answered By: Anatoly E

Answer #5:

There is a new library called furl. I find this library to be most pythonic for doing url algebra.
To install:

pip install furl


from furl import furl
f = furl("/abc?def='ghi'") 
print f.args['def']
Answered By: Mayank Jaiswal

Answer #6:

I know this is a bit late but since I found myself on here today, I thought that this might be a useful answer for others.

import urlparse
url = ''
parsed = urlparse.urlparse(url)
params = urlparse.parse_qsl(parsed.query)
for x,y in params:
    print "Parameter = "+x,"Value = "+y

With parse_qsl(), “Data are returned as a list of name, value pairs.”

Answered By: iCanHasFay

Answer #7:

The url you are referring is a query type and I see that the request object supports a method called arguments to get the query arguments. You may also want try self.request.get('def') directly to get your value from the object..

Answered By: Senthil Kumaran

Answer #8:

def getParams(url):
    params = url.split("?")[1]
    params = params.split('=')
    pairs = zip(params[0::2], params[1::2])
    answer = dict((k,v) for k,v in pairs)

Hope this helps

Answered By: inspectorG4dget

Leave a Reply

Your email address will not be published.