I want to locate all the child element using tag name 'li', and then filter them using id. How to do this.

Lets say i have 4 child elements with tag name 'li' and each of them have class. I want to filter the class and get only 2 types of them.

How to do this. Kindly suggest.

  • Welcome to the site! What have you tried so far? We can help you more if you share your approach, code etc. You can google some basics and try to put things together. If you get stuck, you ask here. – puzzle Nov 8 at 11:48
  • You're saying that you want to filter elements by id and at the same time later you're saying that you have class attribute and you want to filter by class. – wec Nov 8 at 13:49

Python has a feature called List Compreenshion, aimed at creating lists from other lists, after applying some processing on each element.

1 - Find the li elements:

li_items = driver.find_elements_by_class_name("li")

2 - Filter in only element with a given class:

li_items_with_class = [ item for item in list_items if "my_class" in item.get_attribute("class")]

item for item => Simply add the item on the results

in list_items => From this list

if "my_class" in item.get_attribute("class") => If this item has "my_class" on the "class" attribute


This can be done with extra filtering in Python, but the usual straightforward way is to add an extra condition to your CSS selector:

all_items = driver.find_elements_by_css_selector("ul > li")


filtered_items = driver.find_elements_by_css_selector("ul > li.myclass")

where . is a class selector.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.