How to select element by class when multiple elements match?



  • If I select flight departure time with class name through selenium in python but class name is used by both div & span tags it fails.

    How can I select only one element type (div) and not sdpans.

    my code is:

    [element.text for element in self.browser.find_elements(By.CLASS_NAME, "dept-time")]
    


  • To select the div with the class you can use css (preferred for readability)

    BY.css
    

    Example

    driver.find_element(By.CSS, 'div.dept-time')
    

    or xpath

    BY.xpath
    

    Example

    driver.find_element(By.XPATH, '//div[@class=dept-time]
    

    or if there are multiple classes for that element, use

    contains
    

    Example

    //div[contains(@class, 'dept-time')]
    

    If more than 1 div element with that class exist and you want the first one you can also use:

    [1]
    

    Example (XPATH)

    //div[@class='dept-time'])[1]
    

    Example (CSS)

    div.dept-time:first
    

Log in to reply
 

Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2