Selenium Automation- how to iterate through the class element

23 Views Asked by At

How to iterate through multiple class elements using selenium python

launch_box = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[contains(@class, 'launch-button') and contains(@class, 'ml-2') and contains(@class, 'btn') and contains(@class, 'btn-link')]")))

I want to access either 3rd or 4th element in that class. How should I do it?

2

There are 2 best solutions below

0
CatBraaain On

you can use lambda which return element as a arg of element_to_be_clickable()

launch_box = WebDriverWait(driver, 20).until(
  EC.element_to_be_clickable(
    lambda driver: driver.find_elements(By.XPATH,"//button[contains(@class, 'launch-button') and contains(@class, 'ml-2') and contains(@class, 'btn') and contains(@class, 'btn-link')]")[3]
  )
);

and maybe this simple selector works for you

launch_box = WebDriverWait(driver, 20).until(
  EC.element_to_be_clickable(
    lambda driver: driver.find_elements(By.CSS_SELECTOR,"button.launch-button.ml-2.btn.btn-link")[3]
  )
);
0
JeffC On

You can return a collection of the elements and then access them using array notation, e.g.

launch_boxes = wait.until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "button.launch-button.ml-2.btn.btn-link")))
launch_boxes[3].click()

NOTE: I changed the locator to a CSS selector because the syntax is much simpler, shorter, and easier to read.

Reference:
CSS selectors