我有一个菜单,它在鼠标悬停时显示一个列表,我想单击“注销”。 我已经编写了一些代码,但无法获得所需的结果。
这是我的 Java 代码:
public void Logout() throws Exception {
WebElement profileDropdown = driver.findElement(By.className("profile-dropdown"));
//profileDropdown.click();
//profileDropdown.findElement(By.id("lnkLogout")).click();
//Select oSelect = new Select(driver.findElement(By.className("profile-dropdown")));
//oSelect.selectByVisibleText("Log Out");
//List<WebElement> li = profileDropdown.findElements(By.id("lnkLogout"));
//li.get(0).click();//If there are only two such element, here 1 is index of 2nd element in list returned.
List<WebElement> elems = driver.findElements(By.cssSelector("ul>li>a"));
elems.get(5).click();
//profileDropdown.findElement(By.xpath("(//a[contains(text(),'Log Out')])[2]")).click();
}
我已经尝试了很多东西,你可以看到注释的代码行。什么都不适合我。
这是我的 HTML 代码,我正在执行自动化
<div style="display: none;" class="profile-dropdown">
<ul>
<li><a href="https://consumers.keenu.pk/index.php/profile/">My Profile <!--<label id="lblProfilePercentage">0</label>--></a></li>
<li><a href="https://consumers.keenu.pk/index.php/transactionhist/">Transaction History</a></li>
<li><a href="https://consumers.keenu.pk/index.php/customer-care/helpline">Helpline</a></li>
<li><a href="https://consumers.keenu.pk/index.php/pin-pass/">PIN & Password</a></li>
<li><a href="https://consumers.keenu.pk/index.php/settings/">Favorites</a></li>
<li><a href="#" id="lnkLogout" style="cursor:pointer">Log Out</a></li>
</ul>
</div>
它能够找到“profile-dropdown”元素,但随后抛出异常并且无法找到列表元素。
请帮助。
最佳答案
如果您说当您在菜单上执行 mousehoever 时会出现您的菜单项,那么单击它是行不通的。你需要:
1.鼠标先悬停在菜单上
2.需要等到注销菜单项(链接)可见
3.点击它。
Actions action = new Actions(driver);
action.moveToElement(profileDropdown).build().perform();
WebDriverWait wait = new WebDriverWait(driver, 30);
WebElement logoutLink = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("lnkLogout")));
logoutLink.click();
关于java - 如何在 Selenium 中选择 div->ul->li 中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45236944/