Selenium - upload file to iframe

一世执手 提交于 2019-12-06 10:11:47

问题


I have a test which has method to upload file in form located in iframe.

The problem is that test not stable and sometimes fails with the error (run three times to get error example, third run failed):

def fill_offer_image(self):
    driver = self.app.driver
    driver.switch_to.frame(driver.find_elements_by_name("upload_iframe")[3])
E       IndexError: list index out of range

I have implicitly wait = 10 and as you can consider few iframes on the page with the same class so I've been forced to use arrays. And sometimes not all (or all?) iframes loaded.

Does someone have thoughts how to improve stability of that test? Could it relate to mechanics of iframe itself?


回答1:


Lets try this by giving some time for iframe to load by inserting the below code

Import time

## Give time for iframe to load ##
time.sleep(xxx)

hope this will work




回答2:


I would use an Explicit Wait and wait until the count of frame elements with name="upload_iframe" becomes 4 by writing a custom expected condition:

from selenium.common.exceptions import StaleElementReferenceException
from selenium.webdriver.support import expected_conditions as EC

class wait_for_n_elements(object):
    def __init__(self, locator, count):
        self.locator = locator
        self.count = count

    def __call__(self, driver):
        try:
            count = len(EC._find_elements(driver, self.locator))
            return count == self.count
        except StaleElementReferenceException:
            return False

Usage:

wait = WebDriverWait(driver, 10)
wait.until(wait_for_n_elements((By.NAME, 'upload_iframe'), 4))

driver.switch_to.frame(driver.find_elements_by_name("upload_iframe")[3])  


来源:https://stackoverflow.com/questions/29940783/selenium-upload-file-to-iframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!