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 urllib module.
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]
print(captured_value)
We have the url that we want to parse the query string part for.
To do that, we call urlparse with the url.
Then we call parse_qs on the query string part of the URL which is stored in parsed_url.query.
And finally we get the value by the key with parse_qs(parsed_url.query)['some_key'][0] .
Therefore, captured_value is 'some_value'.
Conclusion
To retrieve parameters from a URL with Python, we can use the urllib module.