Selenium无法找到动态网页元素

时间:2015-02-26 05:56:18

标签: java selenium dynamic selenium-webdriver

我正在尝试用Java编写一个用于Web应用程序的Selenium测试脚本。该应用程序有一个按钮,可以在屏幕上动态添加表单域。我遇到的问题是我似乎无法让Selenium Web Driver识别新的表单元素元素。我首先尝试使用@FindBy初始化构造函数中的元素,如下所示:

@FindBy(how = How.CSS, using = "#WIN_0_536870929") private WebElement form;

然后,我尝试使用显式等待来确保元素已加载(在将表单添加到DOM的按钮上):

WebDriverWait webDriverWait = new WebDriverWait(this.getDriver(), 20);
WebElement formButton = webDriverWait.until(ExpectedConditions.elementToBeClickable(By.id("WIN_0_536870929")));
formButton.click();

但无论如何,动态表单元素都无法加载。我得到的错误如下:

org.openqa.selenium.NoSuchElementException:无法找到元素:{“method”:“id”,“selector”:“#WIN_0_817000996”}

更令人困惑的是,当我在调试器中完成测试时,表单字段在测试尝试访问之前完全加载到DOM中。

有没有人知道可能导致这种情况发生的原因?

2 个答案:

答案 0 :(得分:2)

事实证明我试图访问iframe中的元素。非常感谢Vivek Singh建议我调查一下。我能够使用以下代码进入iframe:

this.driver.switchTo().frame(this.driver.findElement(By.cssSelector("#WIN_0_817000899 iframe")));

答案 1 :(得分:-1)

只有在您期望其可见性时才需要定义WebElement:

public static WebElement waitForVisibleElement( WebDriver driver, By locator, int timeOutInSeconds ) {
        WebDriverWait wdw = new WebDriverWait( driver, timeOutInSeconds );
        try {
            return wdw.until( ExpectedConditions.visibilityOfElementLocated(locator) );
        } catch ( NoSuchElementException | TimeoutException | NullPointerException ex ) {
            return null;
        }
    }
相关问题