【问题标题】:Element not found and else part is executed- Selenium web driver未找到元素并执行其他部分 - Selenium Web 驱动程序
【发布时间】:2014-03-09 02:19:17
【问题描述】:

我正在开发 Selenium WebDriver 并使用 Java。如果我执行注销功能,它不会通过 ID 找到元素。下面是代码:

Log.info("Clicking on Logout button");
//driver.findElement(By.id("moreLink")).click();
if(existsElement("logoutLink") == true) {
    WebElement menuHoverLink = driver.findElement(By.id("logoutLink"));
    actions.moveToElement(menuHoverLink).click().perform();
    Thread.sleep(6000);
}
else { 
    Log.info("element not present");
    System.out.println("element not present -- so it entered the else loop");         
}

下面是 HTML 标签:

<li>
    <a id="logoutLink" href="https://10.4.16.159/index/logout/">Log Out</a>
</li>

【问题讨论】:

  • 首先,如果你的方法existsElement()返回布尔值,你不需要匹配true。其次,是在页面上显示的注销链接,当您执行单击它时,因为它似乎存在于某种叠加层上。最后你为什么要鼠标悬停而不是直接点击??
  • 给出 existsElement 方法的代码。我们可以改进它以适应您的情况。

标签: java jquery html selenium selenium-webdriver


【解决方案1】:

试试这个:

1)

actions.moveToElement(menuHoverLink).perform();
menuHoverLink.click; 

安装于:

actions.moveToElement(menuHoverLink).click().perform();
Thread.sleep(6000);

2) 新方法:

clickWhenTheElementIsClickable(By.id("logoutLink"), 10);

...
        protected void clickWhenTheElementIsClickable(By locator, long timeout) {
            WebDriverWait wait = (WebDriverWait)new WebDriverWait(driver,timeout)
            .ignoring(StaleElementReferenceException.class);
            WebElement element = wait.until(
                    ExpectedConditions.elementToBeClickable(locator));
            element.click();
        }

【讨论】:

    【解决方案2】:

    尝试在 if 条件下使用.size() 方法:

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

    .isEmpty()!

    if(!driver.findElements(By.id("logoutLink")).isEmpty()){
    

    【讨论】:

    • 如果我使用上面的代码得到一些错误。方法 size() 未定义类型 By 和 else 部分我得到错误..请帮助解决这个问题..我selenium 和 java 的新手
    • @Amir 看到更新的不是!, .isEmpty()
    猜你喜欢
    • 1970-01-01
    • 2018-08-15
    • 2015-12-16
    • 1970-01-01
    • 2016-09-28
    • 2022-11-07
    • 2015-09-19
    • 2020-12-29
    • 1970-01-01
    相关资源
    最近更新 更多