In this tutorial, we’ll learn how to check if a query string parameter exists in Python. This task is quite common when working with web applications, APIs, or even script and programming tasks.
Python’s standard library provides tools to help perform this and makes it quite easy. We’ll leverage Python’s urllib module to do the heavy lifting.
Step 1: Import Required Libraries
The first step involves importing the required libraries. For this tutorial, only the urllib library is required. This is a standard Python library hence its installation is not necessary.
1 |
from urllib.parse import parse_qs, urlparse |
Step 2: Parse the URL
Next, parse the url using the urlparse() function. This function is a method in the urllib parse module and it helps to break down the url.
1 |
parsed_url = urlparse('https://example.com/?key=value') |
Step 3: Extract Query String Parameters
After this step, extract the parameters present. The query parameters can be accessed using the query attribute of the urlparse object.
1 |
parsed_query = parse_qs(parsed_url.query) |
Step 4: Check Query String Parameters
The final step is to check if a query string parameter exists. Use the ‘in’ keyword to check if a parameter exists. This returns a boolean value, True if the parameter exists, and False if not.
1 |
print('key' in parsed_query) |
So, the entire script will look something like this
1 2 3 4 5 6 7 8 9 10 |
from urllib.parse import parse_qs, urlparse # Parsing the URL parsed_url = urlparse('https://example.com/?key=value') # Extracting Query String parsed_query = parse_qs(parsed_url.query) # Checking if Query String Parameter Exists print('key' in parsed_query) |
Running the script will then verify if the specified query string parameter is present. The output for the above script will be
True
Conclusion
In conclusion, Python’s standard library urllib, specifically urlparse and parse_qs functions, enables us to check if a query string parameter exists in a URL. This is handy in scenarios that require working with URLs and checking their parameters.