Kenito
Kenito

Reputation: 53

Python Code to Parse & Retrieve value from URL string

I have some Dot Net code that parses and retrieves a value from a URL string.

However, I would like to perform the same function but now use python code instead.

Dot Net code snippet is below:

string queryString = string.Empty;
string application_id = string.Empty;
string currentURL = Browser.getDriver.Url;
Uri url = new Uri(currentURL);
string query_String = url.Query;
application_id = query_String.Split(new char[] { '=' }).Last();

Thanks in advance

Upvotes: 1

Views: 1433

Answers (2)

PaulMcG
PaulMcG

Reputation: 63709

Always best to use std lib functions if they are available. Python 3 has urllib.parse (if you are still on Py2, it's urlparse). Use the urlparse method of this module to extract the query part of the url (the stuff after the '?'). Then parse_qs will convert this query to a dict of key:list values - the values are lists to handle query strings that have repeated keys.

url = 'http://www.somesite.blah/page?id=12345&attr=good&attr=bad&attr=ugly'

try:
    from urllib.parse import urlparse, parse_qs
except ImportError:
    # still using Python 2? time to move up
    from urlparse import urlparse, parse_qs

parts = urlparse(url)
print(parts)
query_dict = parse_qs(parts.query)
print(query_dict)
print(query_dict['id'][0])

prints:

ParseResult(scheme='http', netloc='www.somesite.blah', path='/page', params='', 
            query='id=12345&attr=good&attr=bad&attr=ugly', fragment='')

{'attr': ['good', 'bad', 'ugly'], 'id': ['12345']}
12345

Upvotes: 2

Romaine Carter
Romaine Carter

Reputation: 655

first, last = query_String.split('=')

Upvotes: 0

Related Questions