1

I want to count divs inside one div with selenium.

enter image description here

This is my code so far, but I don't understand why this is not working. It returns length of 0.

available = len(browser.find_elements_by_xpath("//div[@class='sc-AykKC.sc-AykKD.slug__RaffleContainer-sc-10kq7ov-2.eujCnV']/div"))
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
adri567
  • 533
  • 5
  • 20

2 Answers2

2

To count <div> tags with value of alt attribute as Closed within its parent <div> using Selenium you can use either of the following based Locator Strategies:

  • Using text():

    available = len(browser.find_elements_by_xpath("//h2[text()='List']//preceding::div[1]//div[@alt='Closed']"))
    
  • Using contains():

    available = len(browser.find_elements_by_xpath("//h2[contains(., 'List')]//preceding::div[1]//div[@alt='Closed']"))
    

Ideally, you have to induce WebDriverWait for visibility_of_all_elements_located() and you can use either of the following Locator Strategies:

  • Using text():

    available = len(WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//h2[text()='List']//preceding::div[1]//div[@alt='Closed']"))))
    
  • Using contains():

    available = len(WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//h2[contains(., 'List')]//preceding::div[1]//div[@alt='Closed']"))))
    
  • 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
    
kjhughes
  • 106,133
  • 27
  • 181
  • 240
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
2

You can try this

div = d.find_element(By.XPATH, '//div[@class='sc-AykKC.sc-AykKD.slug__RaffleContainer-sc-10kq7ov-2.eujCnV']')

res = list(div.find_elements(By.TAG_NAME, 'div'))

print(len(res))
Somesh
  • 21
  • 1