Selenium - 将文件上传到iframe

Selenium - upload file to iframe

我有一个测试可以上传位于 iframe 的表单中的文件。

问题是测试不稳定,有时会失败并出现错误(运行三次获得错误示例,第三次运行失败):

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

我有 implicitly wait = 10 并且您可以考虑页面上很少有相同 class 的 iframe,所以我不得不使用数组。有时并非所有(或所有?)iframe 都已加载。

有人想过如何提高该测试的稳定性吗? 它可能与 iframe 本身的机制有关吗?

我会使用 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

用法:

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])  

让我们通过插入以下代码给 iframe 加载一些时间来尝试一下

Import time

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

希望这会奏效