1

I am using selenium to check a value in a json request and I'm getting an error. What I am doing is first logging in as I can't get a response unless I am logged in. Then I am trying to grab a balance from the json for the user and print it so I can see that it actually worked. It is looking like a big nope.

The json looks like this:

{
  "account": {
     "balance": "28590",
     "status": "0"
  }
}

And here is my code:

from selenium import webdriver
import openpyxl
import json
import requests

driver = webdriver.Firefox(executable_path= r"geckodriver path")
baseURL = 'url'

#Get username/password from excel sheet
workbook = openpyxl.load_workbook(r"xlsx")
sheet = workbook.get_sheet_by_name('Sheet1')
username = str(sheet['A1'].value)
password = str(sheet['B1'].value)

#Open browser
driver.get(baseURL)
driver.maximize_window()

#Login
driver.find_element_by_xpath('xpath').click()
driver.implicitly_wait(500)
driver.find_element_by_id('email').send_keys(username)
driver.find_element_by_id('password').send_keys(password)
driver.find_element_by_id('login').click()

#Check balance
balance_api = 'balance/json'
json_data = requests.get(balance_api).json()
balance = json_data['account'][0]['balance']
print(balance)

Which gives me this error message:

Traceback (most recent call last):
File "pointsCheck.py", line 31, in <module>
balance = json_data['account'][0]['balance']
KeyError: 0

I'm not having any issues with the login. It's all when I try to grab the balance. I'm not sure if this is even the correct way to do this. I appreciate any help.

3
  • 1
    Why do you think account contains a sequence? Commented Oct 25, 2017 at 1:34
  • Looks like it should just be json_data['account']['balance']... Commented Oct 25, 2017 at 1:36
  • @IgnacioVazquez-Abrams I had watched a tutorial and they explained that I needed that but I see that everyone is saying that is the first thing that is wrong. Commented Oct 25, 2017 at 15:39

1 Answer 1

2

You should use json_data['account']['balance']

It's not an array that you need to have the 0 index.

Sign up to request clarification or add additional context in comments.

4 Comments

I removed the [0] but now it is saying KeyError: 'balance'
Can you see what the output of json_data['account'] is, and post it here?
When I do that, I get the json but it's the error that displays when you are logged out and try to access it. So I'm not sure if I'm not waiting long enough to access it or?
@AbidHasan I have similar code but instead of ['balance'] there is a unique value. how do I deal with the unique value

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.