I have:
url = 'http://example.com/json?key=12345&lat=52.370216&lon=4.895168&status=upcoming&radius=20&offset=0'
How can I parse the value 20 for the parameter radius?
I think it is not possible with urlparse.parse_qs(), isn't it?
Also is there a better way rather than using regex?
Konrad Rudolph
550k142 gold badges968 silver badges1.3k bronze badges
asked Sep 4, 2013 at 11:14
Diolor
13.5k31 gold badges121 silver badges184 bronze badges
1 Answer 1
Yes, use parse_qs():
Parse a query string given as a string argument (data of type application/x-www-form-urlencoded). Data are returned as a dictionary. The dictionary keys are the unique query variable names and the values are lists of values for each name.
>>> from urlparse import parse_qs
>>> url = 'http://example.com/json?key=12345&lat=52.370216&lon=4.895168&status=upcoming&radius=20&offset=0'
>>> parse_qs(url)['radius'][0]
'20'
UPD: as @DanielRoseman noted (see comments), you should first pass url through urlparse:
>>> from urlparse import parse_qs, urlparse
>>> parse_qs(urlparse(url).query)['radius'][0]
'20'
answered Sep 4, 2013 at 11:16
alecxe
476k127 gold badges1.1k silver badges1.2k bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Daniel Roseman
This won't work if
radius was the first parameter after the ?, because parse_qs doesn't ignore the rest of the URL. Really you should pass it through urlparse first: urlparse.parse_qs(urlparse.urlparse(url).query)['radius']alecxe
@DanielRoseman didn't know that. Thank you, will include into the answer.
lang-py