我正在使用Selenium WebDriver并使用Java。如果我执行Logout功能,则不会通过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>
答案 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();
}