How to get a list of the <li> elements in an <ul> with Selenium using Python?

kramer65 picture kramer65 · Feb 9, 2015 · Viewed 53.4k times · Source

I'm using Selenium WebDriver using Python for UI tests and I want to check the following HTML:

<ul id="myId">
    <li>Something here</li>
    <li>And here</li>
    <li>Even more here</li>
</ul>

From this unordered list I want to loop over the elements and check the text in them. I selected the ul-element by its id, but I can't find any way to loop over the <li>-children in Selenium.

Does anybody know how you can loop over the <li>-childeren of an unordered list with Selenium (in Python)?

Answer

Mark Rowlands picture Mark Rowlands · Feb 9, 2015

You need to use the .find_elements_by_ method.

For example,

html_list = self.driver.find_element_by_id("myId")
items = html_list.find_elements_by_tag_name("li")
for item in items:
    text = item.text
    print text