0
votes

I've been trying for ages to switch out of an iframe in selenium for python, I've tried every switch_to there is, but to no avail. The error I'm getting is when I switch to the second iframe ("iframe")[1]. I get an index error because for some reason it doesn't switch out of the first iframe. This is the code I have at the moment.

main_win = driver.current_window_handle
driver.switch_to.frame(driver.find_elements_by_tag_name("iframe")[0])
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID ,"btn1"))).click()

sleep(2)

# This is some of the different things I have tried, of course I've tried them separately. I've tried every variation there is of every switch_to* and it hasn't worked at all.
driver.switch_to.parent_frame
driver.switch_to.default_content 
driver.switch_to.(main_win)

sleep(2)
driver.switch_to.frame(driver.find_elements_by_tag_name("iframe")[1])
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID ,"btn2"))).click()

When debugging I tried commenting out everything but the last 2 lines, and then it worked. It switched to the second iframe and clicked "btn3" with no problems. It's clear that the error lies in the switching out of the the first iframe. Thank you very much for helping, this is very frustrating

1
I may be wrong, but isn't it driver.switch_to.default_content()?Sri
Thank you so much! That fixed it! Still confused to as why the driver.current_window_handle didn't work though.user13303513
I'm not too sure, but glad it workedSri
@user13303513: You are dealing with iframes not multiple windows , driver.current_window_handle is used to returns the handle of the current window and its windely use when user want to deal with multiple windows, where as driver.switch_to.default_content() is used to switch back parent page. iframe is a part outside the page and to access it we need to switch webdriver to iframe to perform action onto the iframe & once you finish your work again you have to switch back to parent page for that you need driver.switch_to.default_content() (return back to top level of the page)SeleniumUser

1 Answers

-1
votes

Hei, vi kan komunisere her >:)