WebdriverIO和Java-IFrame中的org.openqa.selenium.NoSuchElementException

时间:2019-12-27 10:23:19

标签: java selenium-webdriver iframe webdriver webdriverwait

当我尝试获取元素“电子邮件”时,我遇到异常(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);

2 个答案:

答案 0 :(得分:1)

要将字符序列发送到电子邮件元素,因为所需元素位于<iframe>中,因此您必须:

  • 为所需的frameToBeAvailableAndSwitchToIt()诱导 WebDriverWait
  • 为所需的elementToBeClickable()诱导 WebDriverWait
  • 您可以使用以下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的相关讨论

答案 1 :(得分:0)

事实证明代码还可以,但是Chrome driver 78 linux 64位被弄乱了。我已经尝试使用Firefox(geckodriver-0.26.0),它的工作原理很吸引人。

感谢@DebanjanB的帮助