1

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

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

2 Comments

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']
@DanielRoseman didn't know that. Thank you, will include into the answer.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.