Finding elements by class name with Selenium in Python

Rate this post

How can I filter elements that have the same class?

In Python, Selenium provides a method called find_elements_by_class_name to find elements with the same class name. This method returns a list of all elements that match the provided class name.

Let’s say you’re trying to find all paragraphs (<p>) with the class “content”. Here’s how you can do it:

This script will print the text inside each <p> tag with the class “content”. In your case, it should print “Link1.” and “Link2.”.

Remember, Selenium requires a specific driver to interface with the chosen browser. Firefox requires geckodriver, which needs to be installed before the above script can be run.

Also, keep in mind that find_elements_by_class_name returns a list, even if there’s only one match. If you’re certain there’s only one element of interest, use find_element_by_class_name (note the lack of ‘s’ in ‘element’) to get the WebElement directly.

Lastly, it’s recommended to add some error handling to your script to manage situations where the elements are not found. This will make your code more robust and easier to debug.

Happy coding!


Avinash is the Founder of Software Testing Sapiens. He is a blogger and Software Tester who has been helping people to get thier Jobs over a years Now.

Leave a Comment

Copy link