0

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'])
snh_nl
  • 2,877
  • 6
  • 32
  • 62

1 Answers1

1

Thx to Abdul

Tested on array of data and works for all situations.

# get url param
@staticmethod
def get_1_uri_param(url, param=""):
    try:
        if param in url:
            return parse_qs(url)[param][0]
    except:
        return url

# get all url params as array data
@staticmethod
def get_all_uri_params(url):
    try:
        return parse_qs(url)
    except:
        return []
snh_nl
  • 2,877
  • 6
  • 32
  • 62