Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 250
kramer65 Avatar asked Feb 09 '15 16:02

kramer65


People also ask

How does Selenium handle UL and Li?

New Selenium IDE In a webpage, a list is represented by an ul tag and it consists of elements with li tag. Thus the li tag can be said as the child of ul. First, we have to identify the element with ul tag with any locator, then traverse through its li sub-elements with the help of a loop.

How do I find an element that contains specific text in Selenium WebDriver Python?

We can find an element that contains specific text with Selenium webdriver in Python using the xpath. This locator has functions that help to verify a specific text contained within an element. The function text() in xpath is used to locate a webelement depending on the text visible on the page.


2 Answers

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 
like image 103
Mark Rowlands Avatar answered Oct 06 '22 22:10

Mark Rowlands


Strangely enough, I had to use this get_attribute()-workaround in order to see the content:

html_list = driver.find_element_by_id("myId") items = html_list.find_elements_by_tag_name("li") for item in items:     print(item.get_attribute("innerHTML")) 
like image 45
glaucon Avatar answered Oct 06 '22 22:10

glaucon