11 April 2024 Leave a comment Tech-Help
When conducting UI tests with Selenium WebDriver in Python, it’s common to interact with various HTML elements, such as unordered lists (<ul>
) and their items (<li>
). In this guide, we will walk through the process of looping over <li>
elements within a <ul>
and retrieving their text content.
Identifying the Unordered List
Firstly, ensure that you’ve selected the unordered list by its unique identifier (id). Here’s how you can do this:
html_list = driver.find_element_by_id("myId")
Replace "myId"
with the actual id of the unordered list in your HTML document.
Looping Over List Items
Once you have the unordered list element, you can find all the child <li>
elements by using the find_elements_by_tag_name
method. Here’s the step-by-step process:
- Find all
<li>
elements within the unordered list: - Loop over each item to retrieve and print the text content:
items = html_list.find_elements_by_tag_name("li")
for item in items:
text = item.text
print(text)
This method will print the text of each list item to the console.
Alternative Method: Using get_attribute
In some cases, you might need to use a different approach to extract the text content if the standard text retrieval is not working as expected. You can use the get_attribute
method to get the innerHTML
of each list item:
for item in items:
print(item.get_attribute("innerHTML"))
This will output the HTML content inside each <li>
element.
Using List Comprehension
For those who prefer a more Pythonic way, list comprehension can be used to create a list of text contents from the list items:
text_contents = [el.text for el in driver.find_elements_by_xpath("//ul[@id='myId']/li")]
for text in text_contents:
print(text)
This method is concise and efficient, especially when working with multiple elements.
Conclusion
Retrieving the text from list items in an unordered list using Selenium with Python can be accomplished in several ways. Whether you choose the direct loop method, the get_attribute
workaround, or list comprehension, each technique provides a reliable means to access the data within <li>
elements for your UI tests.