NoSuchWindowException when using element_to_be_clickable()

I'm trying to use EC.element_to_be_clickable to select an element and to click on it, but I'm getting the following error message:

NoSuchWindowException: Browsing context has been discarded

This element is inside an iframe ("contentAreaFrame") that is inside another iframe ("isolatedWorkArea").

The frame I'm in before I try to switch to "contentAreaFrame" and "isolatedWorkArea" to run the command below, also happens to contain iframes named "contentAreaFrame" and "isolatedWorkArea".


However, these "frame1" iframes differ in that they contain a different number of iframe elements. I tried using the code below to make sure that I'd switch to the correct "contentAreaFrame" before trying to find the element I desire:

test_v = 2

while test_v == 2:
    WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.NAME,"contentAreaFrame")))
    test_v = len(get_ids("iframe"))


WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.NAME,"contentAreaFrame")))
WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.NAME,"isolatedWorkArea")))

Despite these efforts to work around this issue, I'm still getting the NoSuchWindowExcepetion error message.

I have used time.sleep() to make sure the page is fully loaded before running the element_is_clickable() command and it worked just fine, but I would like to be able to click it as soon as possible, considering there is a wild variation in the time the page takes to be loaded for some reason.

Any idea on what could be causing this problem? Thanks in advance.

(Dont worry - I'm fully aware I'm pretty bad at coding)