we are trying to create a function that accepts and uri para key and returns an URI param value.
/webshop/&onderdeel=shop&r_id=108&p_id=317
/webshop/?onderdeel=shop&r_id=108&p_id=317
example.com/webshop/?onderdeel=shop&r_id=108&p_id=317
https://example.com/webshop/?onderdeel=shop&r_id=108&p_id=317
?onderdeel=shop&r_id=108&p_id=317
This function captures som examples of above, but not all
Question: is there 1 method that captures all examples? (e.g. we need the value for p_id)
(and while are at it, is there also 1 method that returns all key value pairs?)
# get url param
@staticmethod
def get_uri_param(url, param=""):
try:
return parse.parse_qs(parse.urlparse(url).query)[param][0]
except:
return None
I was trying this below from Retrieving parameters from a URL but this is not working
Practising here on TIO
import urllib.parse as urlparse
from urllib.parse import parse_qs
urls = ['/webshop/&onderdeel=shop&r_id=108&p_id=317','/webshop/?onderdeel=shop&r_id=108&p_id=317','example.com/webshop/?onderdeel=shop&r_id=108&p_id=317','https://example.com/webshop/?onderdeel=shop&r_id=108&p_id=317','?onderdeel=shop&r_id=108&p_id=317']
for url in urls:
parsed = urlparse.urlparse(url)
if 'p_id' in url:
print(parse_qs(parsed.query)['p_id'])