Home > Software design >  WebDriverWait by class name when there are more class with the same name
WebDriverWait by class name when there are more class with the same name

Time:12-01

I’m trying to click on a button that has the same class as other 5 buttons.

This code is working but clicks on the first button that finds the class.

WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, ".com-ex-5"))).click()

How can I click on the 5th button?

This ain’t working :

WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, ".com-ex-5")))[5].click()

CodePudding user response:

presence_of_element_located returns single element. You need to use presence_of_all_elements_located.

So that your code would look like:

WebDriverWait(driver, 10)
    .until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, ".com-ex-5")))[4]
    .click()

P.S. - If you need 5th button then you need to pick element by index 4 since indexing starts from 0 in Python

CodePudding user response:

  1. In case you want to click on an element you have to use element_to_be_clickable expected_conditions, not presence_of_element_located.
  2. In case there is no unique locator for that element (that's strange) you can use XPath to locate that element.
    So, this should work:
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "(//*[contains(@class,'com-ex-5')])[5]"))).click()

And in case there are 5 elements matching this locator and this is the last of them, this can be used:

WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "(//*[contains(@class,'com-ex-5')])[last()]"))).click()
  • Related