Retrieving parameters from a URL


Question

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.

/abc?def='ghi'

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.

1
137
6/1/2016 6:43:28 PM

Accepted Answer

Python 2:

import urlparse
url = 'http://foo.appspot.com/abc?def=ghi'
parsed = urlparse.urlparse(url)
print urlparse.parse_qs(parsed.query)['def']

Python 3:

import urllib.parse as urlparse
url = 'http://foo.appspot.com/abc?def=ghi'
parsed = urlparse.urlparse(url)
print(urlparse.parse_qs(parsed.query)['def'])
212
3/28/2019 11:32:24 AM

import urlparse
url = 'http://example.com/?q=abc&p=123'
par = urlparse.parse_qs(urlparse.urlparse(url).query)

print par['q'][0], par['p'][0]

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon