Select iframe using Python + Selenium Select iframe using Python + Selenium selenium selenium

Select iframe using Python + Selenium


This worked for me with Python (v. 2.7), webdriver & Selenium when testing with iframes and trying to insert data within an iframe:

self.driver = webdriver.Firefox()## Give time for iframe to load ##time.sleep(3)## You have to switch to the iframe like so: ##driver.switch_to.frame(driver.find_element_by_tag_name("iframe"))## Insert text via xpath ##elem = driver.find_element_by_xpath("/html/body/p")elem.send_keys("Lorem Ipsum")## Switch back to the "default content" (that is, out of the iframes) ##driver.switch_to.default_content()


If iframe is dynamic node, it's also possible to wait for iframe appearence explicitly and then switch to it using ExpectedConditions:

from selenium.webdriver.support import expected_conditions as ECfrom selenium.webdriver.support.ui import WebDriverWait as waitdriver = webdriver.Chrome()driver.get(URL)wait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it("iframe_name_or_id"))

If iframe doesn't have @id or @name it can be found as common WebElement using driver.find_element_by_xpath(), driver.find_element_by_tag_name(), etc..:

wait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it(driver.find_element_by_xpath("//iframe[@class='iframe_class']")))

To switch back from iframe:

driver.switch_to.default_content()


What finally worked for me was:

        sel.run_script("$('#upload_file_frame').contents().find('img[alt=\"Humana\"]').click();")

Basically, don't use selenium to find the link in the iframe and click on it; use jQuery. Selenium has the capability to run an arbitrary piece of javascript apparently (this is python-selenium, I am guessing the original selenium command is runScript or something), and once I can use jQuery I can do something like this: Selecting a form which is in an iframe using jQuery