我想点击下拉菜单项出现在悬停,但它不工作。下面是我正在测试的一个HTML网站:
<div id="header-nav" class="skip-content">
<nav id="nav">
<ol class="nav-primary">
<li class="level0 nav-1 first parent">
<a href="http://demo-store.seleniumacademy.com/women.html" class="level0 has-
children">
Women
</a>
<ul class="level0">
<li class="level1 view-all">
<a class="level1" href="http://demo-
store.seleniumacademy.com/women.html">
View All Women
</a>
</li>
<li class="level1 nav-1-1 first">
<a href="http://demo-store.seleniumacademy.com/women/new-
arrivals.html" class="level1 ">
New Arrivals
</a>
</li>
</ul>
</li>
<li class="level0 nav-2 parent">
<a href="http://demo-store.seleniumacademy.com/men.html" class="level0 has-
children">
Men
</a>
<ul class="level0">
<li class="level1 view-all">
<a class="level1" href="http://demo-store.seleniumacademy.com/men.html">
View All Men
</a>
</li>
<li class="level1 nav-2-1 first">
<a href="http://demo-store.seleniumacademy.com/men/new-arrivals.html"
class="level1 ">
New Arrivals
</a>
</li>
<li class="level1 nav-2-2">
<a href="http://demo-store.seleniumacademy.com/men/shirts.html"
class="level1 ">
Shirts
</a>
</li>
<li class="level1 nav-2-3">
<a href="http://demo-store.seleniumacademy.com/men/tees-knits-and-
polos.html" class="level1 ">
Tees, Knits and Polos
</a>
</li>
</ul>
</li>
</ol>
</nav>我缩短了一些代码,但都是一样的,只是里面的文字是不同的。
我做了一个方法,我想要使用,所以我可以点击不同的项目,在导航栏菜单。下面是该方法的代码:
public Subcategory openSubcategory (String subcategoryName){
WebElement ele = driver.findElement(By.cssSelector("li.nav-2"));
Actions action = new Actions(driver);
action.moveToElement(ele).perform();
List<WebElement> subcategories =
driver.findElements(By.cssSelector("a.level1"));
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
for (WebElement element: subcategories) {
if (element.getText().equals(subcategoryName)) {
element.click();
break;
}
}
return new Subcategory(driver);
}下面是我如何在测试中使用它:
@Test
public void OpenMenShirts() {
MainPage mainPage = new MainPage(driver);
mainPage.openSubcategory("Shirts");
Subcategory subcategory = new Subcategory(driver);
}我没有在测试中添加assert,因为它甚至不会点击“恤”。方法查找26个元素,但它不会进入IF块,可能是因为所有26个元素都为空。方法会超过列表的26次->每个--> if -->返回新的子类别,但是不要进入if块。
这是我用来测试的网站:http://demo-store.seleniumacademy.com/
这是下载我的项目(ZIP)的链接,这样您就可以检查我的错误所在:https://wetransfer.com/downloads/d54a4592f07c54a58fa2e4f779fe007820220215134918/b9fd46
发布于 2022-02-15 19:56:43
首先,将鼠标悬停在需要悬停的元素上(移动鼠标,但不需要单击):
WebElement ele = driver.findElement(By.xpath("<xpath>"));
//Creating object of an Actions class
Actions action = new Actions(driver);
//Performing the mouse hover action on the target element.
action.moveToElement(ele).perform();稍后,等待大约1秒或更短的时间,然后单击元素:
Thread.sleep(1000);
// or wait even more
Thread.sleep(1500);
//Find the element you wish to click on:
// In this example find any A tag
// inside a li tag with class that contains 'level0'
WebElement myElm = driver.findElementByCSS
("li[class*='level0'] a");
// click:
myElm.click();https://stackoverflow.com/questions/71132477
复制相似问题