当我尝试获取元素“email”时,遇到异常(org.openqa.selenium.NoSuchElementException)。由于我刚刚开始使用 WebDriver,我可能错过了一些关于这些竞争条件的重要概念。
WebElement login = driver.findElement(By.id("login"));
login.click();
WebElement iFrame = driver.findElement(By.id("iFrame"));
driver.switchTo().frame(iFrame);
WebElement email = driver.findElement(By.id("email"));
email.sendKeys(USERNAME);
我尝试过但没有成功的一些事情:
设置隐式等待:
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
创建一个WebDriverWait:
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement login = driver.findElement(By.id("login"));
login.click();
WebElement iFrame = driver.findElement(By.id("iFrame"));
driver.switchTo().frame(iFrame);
WebElement email = wait.until(presenceOfElementLocated(By.id("email")));
// and WebElement email = wait.until(visibilityOf(By.id("email")));
email.sendKeys(USERNAME);
创建 FluentWait:
WebElement login = driver.findElement(By.id("login"));
login.click();
WebElement iFrame = driver.findElement(By.id("iFrame"));
driver.switchTo().frame(iFrame);
Wait<WebDriver> wait = new FluentWait<>(driver)
.withTimeout(Duration.ofSeconds(30))
.pollingEvery(Duration.ofSeconds(5))
.ignoring(NoSuchElementException.class);
WebElement email = wait.until(d ->
d.findElement(By.id("email")));
email.sendKeys(USERNAME);
我设法让它工作的唯一方法是使用旧的且好的 Thread.sleep() (也丑陋)
WebElement login = driver.findElement(By.id("login"));
login.click();
WebElement iFrame = driver.findElement(By.id("iFrame"));
driver.switchTo().frame(iFrame);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
WebElement email = driver.findElement(By.id("email"));
email.sendKeys(USERNAME);
最佳答案
将字符序列发送到电子邮件元素,因为所需元素位于 <iframe>
内所以你必须:
- 引发WebDriverWait以获得所需的
frameToBeAvailableAndSwitchToIt()
. - 引发WebDriverWait以获得所需的
elementToBeClickable()
. 您可以使用以下 Locator Strategies
driver.findElement(By.id("login")).click(); new WebDriverWait(driver, 10).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.id("iFrame"))); new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.id("email"))).sendKeys(USERNAME);
Here you can find a relevant discussion on Ways to deal with #document under iframe
关于java - WebdriverIO 和 Java - IFrame 中的 org.openqa.selenium.NoSuchElementException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59499273/