未找到元素,否则执行部分 - Selenium Web驱动程序

时间:2014-02-11 10:37:43

标签: java jquery html selenium selenium-webdriver

我正在使用Selenium WebDriver并使用Java。如果我执行Logout功能,则不会通过ID找到元素。以下是代码:

enter image description here

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>

2 个答案:

答案 0 :(得分:0)

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

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

.isEmpty()以及!

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

答案 1 :(得分:0)

试试这个:

1)

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

而不是:

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

OR

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();
        }