Shantanu Rauthan
Shantanu Rauthan

Reputation: 31

How to select an iframe as soon as it appears on the screen in python

I am trying to fill data inside an iframe But the iframe appears anywhere between 15-30 seconds

I have used time.sleep(30)- Works well if the iframe loads at around 25-30 seconds. But sometimes it loads up at 15 seconds and the remaining 15 seconds are wasted

I don't wanna waste time with explicit sleep Is there any other way I can perform action on iframe as soon as it appears in the viewport?

My Code:

driver.find_element_by_xpath("//button[@type='submit'][contains(.,'Submit')]").click()
time.sleep(30)
        
iframe = driver.find_elements_by_tag_name("iframe")
driver.switch_to_frame(iframe[3])
driver.find_element_by_xpath("something").send_keys()
driver.find_element_by_xpath(something).click()
driver.switch_to_default_content()

Upvotes: 0

Views: 55

Answers (2)

Prophet
Prophet

Reputation: 33361

You can use webdriverwait as following:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"(//iframe)[3]")))


driver.find_element_by_xpath("something").send_keys()
driver.find_element_by_xpath(something).click()
driver.switch_to.default_content()

Upvotes: 1

cruisepandey
cruisepandey

Reputation: 29362

You can use that with Explicit waits :

Sample code :

wait = WebDriverWait(driver, 10)
iframe = driver.find_elements_by_tag_name("iframe")
wait.until(EC.frame_to_be_available_and_switch_to_it((iframe[3])))
driver.find_element_by_xpath("something").send_keys()
driver.find_element_by_xpath(something).click()
driver.switch_to.default_content()

Imports :

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

Official docs about Explicit waits

Note that switch_to_default_content() has been deprecated. you will have to use driver.switch_to.default_content() instead.

Upvotes: 0

Related Questions