2

How to get list of URL-parameters from URL? For example: http://example.com/blank.html?access_token=blablabla&expires_in=0&user_id=ablabl&secret=rararar.

I need to get access_token, expires_in, user_id, secret.

1 Answers1

1

Use urlparse.parse_qs() or urlparse.parse_qsl() to parse the query string:

from urlparse import parse_qs, parse_qsl, urlparse

query_string = urlparse(url).query
if query_string:
    data_as_dict = parse_qs(query_string)  # returns a dictionary with lists
    data_as_list = parse_qsl(query_string) # returns a list of tuples

Demo:

>>> from urlparse import parse_qs, parse_qsl
>>> url = 'http://example.com/blank.html?access_token=blablabla&expires_in=0&user_id=ablabl&secret=rararar'
>>> query_string = url.partition('?')[2]
>>> parse_qs(query_string)
{'access_token': ['blablabla'], 'user_id': ['ablabl'], 'secret': ['rararar'], 'expires_in': ['0']}
>>> parse_qsl(query_string)
[('access_token', 'blablabla'), ('expires_in', '0'), ('user_id', 'ablabl'), ('secret', 'rararar')]

Because any key in a query string can occur more than once, you can end up with more than one value per key. The parse_qs() function collects all values into lists per key, the parse_qsl() function simply returns each key-value pair as a tuple, letting you decide what to do with duplicates.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343