如何使用 Java 使用 Selenium WebDriver 获取 <ul> 的所有 <li>?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24719060/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 14:25:21  来源:igfitidea点击:

How to get all the <li> of <ul> with Selenium WebDriver using Java?

javaseleniumselenium-webdriver

提问by user3658696

I am trying to get all the li or ul by following code:

我正在尝试通过以下代码获取所有 li 或 ul:

List <WebElement> we = ffDriver.findElement(By.xpath("//*[@id='sf-menu']/li/a/b"));

but I am facing error Add cast to List <WebElements>when add cast to webelements error pears that can not cast.

但是我在向Add cast to List <WebElements>无法投射的 webelements 错误梨中添加强制转换时遇到错误。

How can I assign all the elements of ul to the List ? in the below css for selenium webdriver with java

如何将 ul 的所有元素分配给 List ?在下面的 css 中使用 java 进行 selenium webdriver

<ul id="sf-menu">

<li class="current">
    <a id="menu_admin_viewAdminModule" class="firstLevelMenu" href="/symfony/web/index.php/admin/viewAdminModule">
        <b>

            Administración

        </b>
    </a>
    <ul></ul>
    <!--

     second level 

    -->
</li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>

回答by alecxe

You need findElements()instead of findElement():

你需要findElements()而不是findElement()

List <WebElement> we = ffDriver.findElements(By.xpath("//*[@id='sf-menu']/li/a/b"));

回答by Nguyen Vu Hoang

You cannot get List by findElement (which returns WebElement). There are only 2 approaches for you

您无法通过 findElement(返回 WebElement)获取 List。只有2种方法适合你

1 - Like elecxe's suggestion (recommended)

1 - 喜欢elecxe的建议(推荐)

2 -

2 -

List<WebElement> we;
we.add(ffDriver.findElements(By.xpath("//*[@id='sf-menu']/li")));
we.add(ffDriver.findElements(By.xpath("//*[@id='sf-menu']/li[2]")));
... 
we.add(ffDriver.findElements(By.xpath("//*[@id='sf-menu']/li[n]")));

回答by Ripon Al Wasim

WebElement ul_Element = driver.findElement(By.id("sf-menu"));
List<WebElement> li_All = ul_Element.findElements(By.tagName("li"));
System.out.println(li_All.size());
for(int i = 0; i < li_All.size(); i++){
System.out.println(li_All.get(i).getText());
}

//OR

//或者

for(WebElement element : li_All){
System.out.println(element.getText());
}