简体   繁体   中英

Create a click event using selenium when there are multiple same class and no id elements using Python

I am trying to create an automated download event for one ERP platform using Selenium in python. This is a bit tricky for this part as there is no specific element to find and click.

Multiple buttons have the same class and no id for the highlighted button (DATABASE/BACKUP)

在此处输入图像描述

Can anyone help me with the same?

event flow >> Login page > click "administration button" > click "database / backup"

thanks

As per Selenium documentation https://selenium-python.readthedocs.io/locating-elements.html you can find all of the elements by their class name and then access them by index ([index_number]).

all_buttons = driver.find_elements_by_class_name("your_class_name")

then you can do something like:

button_to_click = all_buttons[3] # The 4th button which has index 3 in all the retrieved buttons by class name
driver.find_element(By.XPATH,"//a[contains(text(),'Database / Backup')]").click()

Simply click the a tag which contains the text.

To click on the element with text as DATABASE/BACKUP you can use either of the following Locator Strategies :

  • Using xpath :

     driver.find_element(By.XPATH, "//a[@class='menui' and contains(., 'DATABASE/BACKUP')]").click()
  • Using xpath :

     driver.find_element(By.XPATH, "//a[text()[contains(., 'DATABASE/BACKUP')]]").click()

The desired element is a dynamic element, ideally to click on a clickable element you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following Locator Strategies :

  • Using XPATH :

     WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[@class='menui' and contains(., 'DATABASE/BACKUP')]"))).click()
  • Using XPATH :

     WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[text()[contains(., 'DATABASE/BACKUP')]]"))).click()
  • 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM