0

Using Python how can I print request_token from a URL like:

https://kite.trade/?request_token=p87tOTSXRSp4O20TGr870n2JiXFKISIh&action=login&status=success

IE: the text between = to & following request_token.

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135

3 Answers3

1

I think what you're looking for is parse_qs from urllib.parse.

from urllib.parse import urlparse, parse_qs #import stuff

#parse the url
url_obj = urlparse('https://kite.trade/?request_token=p87tOTSXRSp4O20TGr870n2JiXFKISIh&action=login&status=success')
#get a dictionary from the query
q_dict = parse_qs(url_obj.query)
#now get query args by key name. 
print(q_dict["request_token"])
print(q_dict["status"])

Here is a link to the documentation for parse_qs.

0

Use the urlparse library in python 2 https://docs.python.org/2/library/urlparse.html

Or urllib.parse in python 3 https://docs.python.org/3/library/urllib.parse.html

Anthony Manning-Franklin
  • 4,408
  • 1
  • 18
  • 23
0

You can use split the strings using string functions and put the query into a dict like:

Code:

url = 'https://kite.trade/?request_token=p87tOTSXRSp4O20TGr870n2JiXFKISIh&' \
      'action=login&status=success'

query = dict(a.split('=') for a in url.split('?')[1].split('&'))
print(query)

You can do the same using the urllib like:

import urllib
query = urllib.parse.parse_qs(urllib.parse.urlparse(url).query)
print(query['request_token'][0])

Results:

{'request_token': 'p87tOTSXRSp4O20TGr870n2JiXFKISIh', 'action': 'login', 'status': 'success'}
p87tOTSXRSp4O20TGr870n2JiXFKISIh
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
  • @KiranKumarReddy, you are very welcome. However, on SO the very best way to say thanks is to upvote *any* questions or answers you find useful. And on your questions, if one of the answers is a good fit for your problem, you can mark it as the accepted answer. See the [Help Center](http://stackoverflow.com/help/someone-answers) for guidelines. – Stephen Rauch Mar 31 '18 at 16:28