1

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

1
  • We would need more information, will you run your code from within a web-framework as Django or Flask?. Because the last line of your code is almost the same on Python, so I'm assuming that you want the whole funcionality in python: from retrieving URL to strip the id of it. Commented Dec 27, 2016 at 20:41

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

Will give an error if there is more than one parameter in the query string (as in "size=large&color=blue").

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.