我附上了正在测试的应用程序的示例UI图像。 我正在使用带有java的webdriver来获取标题值列表&也可以获得下拉值。
1)使用xpath,我无法获得尺寸&还有ONLY标题的文本值(Test1,Test2,test3,help)
2)其次,Test1具有下拉值,类似于Test2& TEST3。 我应该能够获得test1的大小(应该是4),然后根据XPATH位置获取文本值(Get Class 1 etc ..)。
CODE
Grid.driver().get("https://testpt1qa.com");
// Get Size of the Navigation Header
WebElement parent = Grid.driver().findElement(By.xpath("//nav[@id='main-menu']"));
List<WebElement> child = parent.findElements(By.tagName("li"));
/**
* THIS IS listing all the links under Test1,Test2,Test3 & Help
*/
System.out.println(child.size());
for (WebElement webElement : child) {
String sizeval = webElement.getSize().toString();
System.out.println("********** " + sizeval);
....
....
示例HTML代码
<nav id="main-menu" role="navigation" style="background-color: transparent;">
<ul style="background-color: transparent;">
<li style="background-color: transparent;">
<a id="header-test1" class="selected" aria-controls="submenu-test1" rel="menuitem" href="https://testpt1qa.com" role="button" aria-expanded="true" style="background-color: transparent;">Test1</a>
<div id="submenu-test1" class="menu-wrapper on open done" aria-labelledby="header-test1" role="region" tabindex="-1">
<ul id="header-test1-menu" class="subnav list " style="background-color: transparent;">
<li style="background-color: transparent;">
<a href="https://testpt1qa.com/kp/helper5" style="background-color: transparent;">Get Class 1</a>
</li>
<li>
<a href="https://testpt1qa.com/kp/helper1" style="background-color: transparent;">Get Class 2</a>
</li>
<li>
<a href="https://testpt1qa.com/kp/helper2">Get Class 3</a>
</li>
<li>
<a href="https://testpt1qa.com/kp/helper3">Get Class 4</a>
</li>
<li>
</ul>
.....
.....
根据上面的代码,它会打印所有下拉值和标题值的大小,而不是特定的值。
答案 0 :(得分:1)
您的代码存在的问题是parent.findElements(By.tagName("li"));
会返回li
下的所有<nav id="main-menu"...
元素。下面的代码有点冗长,希望这会有所帮助。
Grid.driver().get("https://testpt1qa.com");
// Get top level parent for all nav elements
WebElement parent = Grid.driver().findElement(By.xpath("//nav[@id='main-menu']//ul//li"));
// Get the main menu items: main-menu > ul > li > a
// At this point you should have Test1, Test2, Test3 and Help.
List<WebElement> menuItems = parent.findElements(By.xpath(".//a[@rel='menuitem'"));
// Get menu items size
System.out.println("Number of menu items " + menuItems.size());
// Get the text for each menu
for (WebElement menuItem : menuItems) {
System.out.println(menuItem.getText());
// Now search for sub menu item by traversing up to the parent of the current menu item
// This should get you Get Class1 etc based on the current menu in the loop
List<WebElement> subMenuItems = menuItem.findElements(By.xpath(".//..//div//ul//li//a"));
System.out.println("Number of sub menu items " + subMenuItems.size());
for (WebElement subMenuItem : subMenuItems) {
System.out.println(subMenuItem.getText());
}
}