Home > Back-end >  How to get all the elements from same class using Selenium
How to get all the elements from same class using Selenium

Time:02-05

I am trying to get span elements from same class names. I am trying to click the lastest avaible days in calender.

My code is :

days = driver.find_element(By.CLASS_NAME,'BookingCalendar-date--bookable')
avaibledays = days.find_elements(By.CLASS_NAME,'BookingCalendar-day')
for i in avaibledays:
    print(i.text)

This work for 1 class when I try to change the days variable like this:

days = driver.find_elements(By.CLASS_NAME,'BookingCalendar-date--bookable')

I can't get all.

There is a calander html.

enter image description here

I want to click a span at lastest class name is = "BookingCalendar-date--bookable"

Span names and class same for Booking-Calendar-date--unavaible

So basicly I'm trying to get multiple span elements from classes name is BookingCalendar-date--bookable. The span elements have a same class name it's = BookingCalendar-day

CodePudding user response:

To extract the texts from all the <td ...> using List Comprehension you can use either of the following locator strategies:

  • Using CSS_SELECTOR:

    print([my_elem.text for my_elem in driver.find_elements(By.CSS_SELECTOR, "td.BookingCalendar-date--bookable span.BookingCalendar-day")])
    
  • Using XPATH:

    print([my_elem.text for my_elem in driver.find_elements(By.XPATH, "//td[@class='BookingCalendar-date--bookable ']//span[@class='BookingCalendar-day']")])
    
  • Note : You have to add the following imports :

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    
  • Related