简体   繁体   中英

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

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

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.

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

<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>

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

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

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

1 - Like elecxe's suggestion (recommended)

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]")));
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());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM