# Checking balance of a travel card with Selenium

A Leap Card is essentially a travel card for Dublin, Ireland that can be used to pay for a bus or tram fare. It has to be topped up and I often forget how much I have left on it.

To get familiar with Selenium, I wrote some code that gets the balance for me. I haven't worked with this framework before, so I'd like to know if there's room for improvement here.

import json

from selenium import webdriver

def get_credentials():
"""Get user credentials from a JSON file"""
with open('auth.json', 'r') as f:

class LeapHandler:
"""Class to handle any interactions with Leap Card website"""

def __init__(self):
self.driver = webdriver.Chrome()

def get_balance(self):
"""Return current Leap Card Balance"""
balance = self.driver.find_element_by_css_selector('div.pull-left').text
return balance

if __name__ == '__main__':
lh = LeapHandler()
balance = lh.get_balance()
print(f'LepaCard balance is €{balance}')


Your code is actually quite clean and readable, good job. Here are some of the things I would consider changing:

• you can simplify get_credentials() a bit, using the tuple packing/unpacking:

def get_credentials():
"""Get user credentials from a JSON file."""
with open('auth.json', 'r') as f:

• div.pull-left does not look like a good quality locator. It may work now, but this locator is fragile because it is design-specific (pull-left is a bootstrap class used for page layout). See if this element has an id or a data-oriented class or a data-oriented attribute.
• Using the div.pull-left locator is a workaround, as I couldn't get the text any other way. Here is the snippet from page source: pastebin.com/Z3Kec3zD – Lukasz Salitra Jul 31 '17 at 21:24
• @LukaszSalitra right, not the easiest markup to deal with. I would probably use a preceding label with, for example, an XPath - something like: //div[contains(label/@id, "TravelCreditBalance")]/following-sibling::div/div - not the simplest expression though. Looking at that, your workaround looks better, doesn't it? :) – alecxe Jul 31 '17 at 21:32