MortenB
MortenB

Reputation: 3529

selenium python return data from javascript window object

How can I get hold of the following object in python selenium:

(in firefox/Chrome console):
>>window.Alarms.alarmData
Array [ {…}, {…} ]

This returns empty:

alarm = driver.execute_script("return window.Alarms.alarmData;")
print(alarm)
[]

Upvotes: 3

Views: 2233

Answers (2)

MortenB
MortenB

Reputation: 3529

With the help of @Andersson I found this issue. When starting window.Alarms.AlarmData is defined as an empty list '[]', so it will be successfully returned, I just need to wait until it is no longer an empty list, The important lession was to check initial state of variables, because they may be defined and just successfully in selenium.

def test2_alarmdata(self):
    """ fetch the data objects """
    driver = self.driver
    cookie_read(driver)
    driver.get(default['url'] + "/alarm_board/index.html")
    alarmData = None
    retries = args.retries
    while not alarmData and retries:
        time.sleep(1)
        alarms = driver.execute_script("return window.Alarms.alarmData;")
        if alarms:
            alarmData = alarms
        retries -= 1
    if isinstance(alarmData, list):
        print("we have {} queued alarms".format(len(alarmData)))

Run the unittest:

we have 2 queued alarms
__main__.T.test2_alarmdata (3.4068s)

Upvotes: 1

Andersson
Andersson

Reputation: 52665

You can try to wait until JS object returns any non-empty value:

from selenium.webdriver.support.ui import WebDriverWait

alarm = WebDriverWait(driver, 20).until(lambda driver: driver.execute_script("return window.Alarms.alarmData;"))

Upvotes: 3

Related Questions