Sometimes, we want to retrieve parameters from a URL with Python.
In this article, we’ll look at how to retrieve parameters from a URL with Python.
How to retrieve parameters from a URL with Python?
To retrieve parameters from a URL with Python, we can use the parse_qs function.
For instance, we write
from urllib.parse import urlparse
from urllib.parse import parse_qs
url = 'https://www.example.com/some_path?some_key=some_value'
parsed_url = urlparse(url)
captured_value = parse_qs(parsed_url.query)['some_key'][0]
to call urlparse with the url string to parse the URL into an object.
Then we get the query string with parsed_url.query.
And we call parse_qs with the returned query string to parse it into a dict.
Finally, we get the value with key some_key from the query string and use [0] to get the first returned entry.
Conclusion
To retrieve parameters from a URL with Python, we can use the parse_qs function.