Most answers here suggest using parse_qs
to parse an URL string. This method always returns the values as a list (not directly as a string) because a parameter can appear multiple times, e.g.:
http://example.com/?foo=bar&foo=baz&bar=baz
Would return:
{'foo': ['bar', 'baz'], 'bar' : ['baz']}
This is a bit inconvenient because in most cases you're dealing with an URL that doesn't have the same parameter multiple times. This function returns the first value by default, and only returns a list if there's more than one element.
from urllib import parse
def parse_urlargs(url):
query = parse.parse_qs(parse.urlparse(url).query)
return {k:v[0] if v and len(v) == 1 else v for k,v in query.items()}
For example, http://example.com/?foo=bar&foo=baz&bar=baz
would return:
{'foo': ['bar', 'baz'], 'bar': 'baz'}
import urllib.parse as urlparse
– Panda