Selenium 找不到动态网页元素
Selenium can't find dynamic web element
我正尝试在 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 中。
有谁知道是什么导致了这种情况发生?
仅当您期望其可见性时才必须定义 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;
}
}
原来我是在尝试访问 iframe 中的元素。非常感谢 Vivek Singh 建议我对此进行调查。我能够使用这行代码进入 iframe:
this.driver.switchTo().frame(this.driver.findElement(By.cssSelector("#WIN_0_817000899 iframe")));
我正尝试在 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 中。
有谁知道是什么导致了这种情况发生?
仅当您期望其可见性时才必须定义 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;
}
}
原来我是在尝试访问 iframe 中的元素。非常感谢 Vivek Singh 建议我对此进行调查。我能够使用这行代码进入 iframe:
this.driver.switchTo().frame(this.driver.findElement(By.cssSelector("#WIN_0_817000899 iframe")));