How to extract parameters from a URL in Python
Published on Aug. 22, 2023, 12:15 p.m.
To extract parameters from a URL in Python, you can use the urllib.parse
module. Here’s an example:
from urllib.parse import urlparse, parse_qs
url = 'https://www.example.com/page?param1=value1¶m2=value2'
# parse the URL to get the query string
query_string = urlparse(url).query
# parse the query string to get the parameter values
params = parse_qs(query_string)
# access the parameter values by name
param1_value = params['param1'][0]
param2_value = params['param2'][0]
print(param1_value)
print(param2_value)
In this example, we first use urlparse()
to extract the query string from the URL. We then use parse_qs()
to parse the query string and extract the parameter values as a dictionary. Finally, we access the parameter values by name using the dictionary syntax.