当我尝试获取元素“电子邮件”时,我面临异常(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);
向email元素发送字符序列,因为所需的元素在<iframe>
之内,因此您必须:
frameToBeAvailableAndSwitchToIt()
。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);
在这里您可以找到有关Ways to deal with #document under iframe的讨论