Home > Software engineering >  How to obtain the number of elements with classname "xyz" through Selenium
How to obtain the number of elements with classname "xyz" through Selenium

Time:07-24

Is it possible to do something like this? I want to know the number of elements with the class property set to 'gsc-cursor-page'.

pages_nav = driver.find_element_by_css_selector('.gsc-cursor')
pages = driver.find_element_by_css_selector('.gsc-cursor-page')
for pages in pages_nav:
    print("len(pages)")

As shown below are (.gsc-cursor-page) inside (.gsc-cursor) So how can I obtain the number of elements with classname 'gsc-cursor-page'.

Navbar

CodePudding user response:

I think you can simply do

pages = driver.find_elements_by_css_selector('.gsc-cursor-page')

find_elements instead of find_element, which returns a list. And then you can count the number of elements in the list with

len(pages)

CodePudding user response:

To print the number of elements with classname property set to gsc-cursor-page you can use either of the following locator strategies:

  • Using CLASS_NAME:

    print(len(driver.find_elements(By.CLASS_NAME, "gsc-cursor-page")))
    
  • Using CSS_SELECTOR:

    print(len(driver.find_elements(By.CSS_SELECTOR, "[class='gsc-cursor-page']")))
    
  • Using XPATH:

    print(len(driver.find_elements(By.XPATH, "//*[@class='gsc-cursor-page']")))
    
  • Related