Selenium - upload file to iframe

2019-04-13 03:18发布

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?

2条回答
干净又极端
2楼-- · 2019-04-13 03:36

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

查看更多
Summer. ? 凉城
3楼-- · 2019-04-13 03:37

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])  
查看更多
登录 后发表回答