1

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'.

Html code

AnxiousDino
  • 187
  • 15

2 Answers2

1

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']")))
    

Update

The output of 15, 13 and 13 is perfect as the xpath and the css_selector looks for the elements only with classname gsc-cursor-page i.e. perfect match and there can be some more elements outside the scope of the snapshot you provided and some more elements which also contains the classname gsc-cursor-page.


Solution

Your effective line of code will be:

  • Using CSS_SELECTOR:

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

    print(len(driver.find_elements(By.XPATH, "//div[@class='gsc-cursor']//div[@class='gsc-cursor-page']")))
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
  • 2
    Thanks, but they do not return the expected value. They return 15, 13 and 13. I have updated the picture of the html tags. There are a total of 10 elements with the classname 'gsc-cursor-page' wihin the 'gsc-cursor' class. – AnxiousDino Jul 23 '22 at 23:55
  • 3
    Yeah you are right, there are other elements named under same syntax. But I just had to move futher out in the scope of the CSS_SELECTOR path. By running print(len(driver.find_elements(By.CSS_SELECTOR, "div.gsc-resultsRoot.gsc-tabData.gsc-tabdActive div.gsc-cursor-box.gs-bidi-start-align div.gsc-cursor div.gsc-cursor-page"))) I will get the expected result. Thanks for showing the way :) GG. – AnxiousDino Jul 24 '22 at 00:31
0

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)
Araxide
  • 26
  • 4
  • Nope, it returns a result of 142 when it should be 10 – AnxiousDino Jul 23 '22 at 23:36
  • Then you probably need to update css selector or xpath selector for something more precise, however this answer gets you the number of elements with classname "xyz" – Araxide Jul 24 '22 at 06:47