【问题标题】:IF statement in Selenium WebdriverSelenium Webdriver 中的 IF 语句
【发布时间】:2015-05-21 14:58:03
【问题描述】:

我想知道是否有人可以帮助我解决我正在尝试解决的问题以及用于 Webdriver 的 Java 中的 If 语句。

登录我正在测试的应用程序时,可能会在主页之前进入安全问题页面(如果是新用户等)。我希望测试中的代码在出现安全问题页面时填写并继续,如果没有,请检查您是否在主页上。

我可以在 Selenium RC 中使用

 if (selenium.isTextPresent("User Account Credentials Update")) {   
            selenium.type("//input[@id='securityQuestion']", "A");
            selenium.type("//input[@id='securityAnswer']", "A");
            selenium.type("//input[@id='emailAddress']", "test@test.com");
            selenium.click("update");
            selenium.waitForPageToLoad("30000");
            }


 assertTrue(selenium.isTextPresent("MainPage"));

玩弄我正在使用的 Webdriver:

    if(driver.findElement(By.id("securityQuestion")) != 0) {
                driver.findElement(By.id("securityQuestion")).sendKeys("A");
                driver.findElement(By.id("securityAnswer")).sendKeys("A");
                driver.findElement(By.id("emailAddress")).sendKeys("test@test.com");
                driver.findElement(By.id("update")).click();

Assert.assertTrue("Main Page is not Showing",
            driver.getPageSource().contains("MainPage"));

这样做的问题是,如果未显示安全屏幕,它总是会抛出异常。如果没有显示该页面,我需要如何设置代码以便它忽略安全页面内容? 谢谢你的帮助:-)

【问题讨论】:

  • 你遇到了什么异常?

标签: java selenium


【解决方案1】:

您可以使用driver.findElements 来检查特定元素是否存在而不会引发异常。这是有效的,因为如果没有找到任何元素,它将返回大小为 0 的 WebElements 列表。目前,如果Selenium 尝试使用findElement 查找元素并且该元素不存在,则会抛出NoSuchElementException 这意味着您可以替换:

if (driver.findElement(By.id("securityQuestion")) != 0)

用这个:

if (driver.findElements(By.id("securityQuestion")).size() != 0)

【讨论】:

  • 我喜欢 .size() 的方法。 findElements() 不会像 findElement() (singular) 那样找到异常。
【解决方案2】:

只要你捕获/处理它,抛出的异常实际上并没有错。

换句话说,我会在这里关注EAFP approach:

try {
    driver.findElement(By.id("securityQuestion"));
    // ...
} catch (NoSuchElementException e) {
    // handle exception, may be at least log in your case
}

【讨论】:

  • 与.findElements() 建议相比,这里的额外好处是,在积极的情况下,这会更快——它不会等待完整的隐式等待。
  • @SiKing .findElements() 和 .findElement() 在声明没有与查询匹配的元素之前,都会尊重驱动程序上设置的任何隐式等待。
  • @Louis 对!这就是为什么我说“在肯定的情况下”。一旦找到第一个,.findElement() 将停止,而.findElements() 将继续等待整个持续时间。
  • @SiKing 对。让我先说一下我应该说的话:.findElements 将在匹配后立即返回,就像 .findElement 一样。
【解决方案3】:

我通常只是把它包装成一个方法:

public boolean elementExists(By selector)
{
    try
    {
        driver.findElement(selector)
        return true;
    }
    catch(NoSuchElementException e)
    {
        return false;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-16
    • 2022-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多