Search code examples
pythonseleniumxpathcss-selectorsclassname

How to locate an element with multiple classnames using Selenium and Python


I'm trying to click on the following element with the class name equals "clean right":

<li class="clean right"></li>

How could I locate it by using driver.find_element_by_class_name()


Solution

  • You can't pass multiple classnames as argument through find_element_by_class_name() and doing so you will face an error as:

    invalid selector: Compound class names not permitted
    

    There are multiple approaches to solve this usecase and you can use either of the following Locator Strategies:

    • If the element is uniquely identified only through the classname clean you can use:

      driver.find_element_by_class_name("clean")
      
    • If the element is uniquely identified only through the classname right you can use:

      driver.find_element_by_class_name("right")
      
    • If both the classnames, clean and right are mandatory to identify the element, you can use as follows:

      driver.find_element_by_css_selector("li.clean.right")
      
    • As an alternative you can also use as follows:

      driver.find_element_by_xpath("//li[@class='clean right']")
      

    tl; dr

    Invalid selector: Compound class names not permitted error using Selenium


    Reference

    Find div element by multiple class names?