27

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

Ripon Al Wasim
  • 36,924
  • 42
  • 155
  • 176
kramer65
  • 50,427
  • 120
  • 308
  • 488

3 Answers3

46

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
Mark Rowlands
  • 5,357
  • 2
  • 29
  • 41
  • By having a variable named `list` you are shadowing a built-in `list` which may cause very weird problems on the way. – alecxe Feb 09 '15 at 18:42
  • Mark, thanks! That seems to work perfectly well. Just one last question; there is actually a link within the tag: `
  • some link
  • `, and I expected `print item.text` to print that link, but it doesn't print anything. Would you know how I would be able to get the html of the link, or maybe select the link and print out the text of the link? Thanks in advance! – kramer65 Feb 09 '15 at 20:56
  • @alecxe I complete agree, but no-one should just copy-paste. :) But I've edited the variable just in case. – Mark Rowlands Feb 10 '15 at 09:52