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

标签 java selenium-webdriver iframe webdriver webdriverwait

当我尝试获取元素“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/

相关文章:

java - 在列上使用别名的查询会出错

Selenium “Element is not clickable at point” 在 Firefox 中出现错误,但在 Chrome 中工作

javascript - 从 src 为外部域的 iframe 中,可以通过 "parent"对象使用哪些方法?

java - 实现线程安全的指数量规

java - 如何在 map 上的地理工具中拖放多个点

java - 单击 jPanel (Java) 时如何调用函数?

java - WebDriver 从页面中删除元素

python - PhantomJS 不提取链接 Selenium

php - 为什么 iframe 内容为空?

javascript - 如何防止用户在 iframe 之外打开我的网络应用程序?