How to loop through only li elements inside a ul

Viewed 8464

Xpath of ul element:

resultSet = driver.find_element_by_xpath("//section[@id='abc']/ul")

How to loop through only li elements inside a ul, given above ul element xpath?

2 Answers

You can search for li nodes starting from already defined ul with below code:

resultSet = driver.find_element_by_xpath("//section[@id='abc']/ul")
options = resultSet.find_elements_by_tag_name("li")

To loop through list of li nodes simply do

for option in options:
    print(option.text)

If you have a HTML like this:

<div class="someclass">
    <ul>
      <li>Item 1</li>
      <li>Item 2</li>
      <li>Item 3</li>
    </ul>
</div>

Than iterating through li item in ul goes like this:

  ulClass= driver.find_element_by_css_selector('div.someclass')

    if ulClass !=None:
        for li in ulClass.find_elements_by_css_selector('ul'):
            print(li.text)
Related