Home > Software engineering >  How to click on an element with an unique attribute using Selenium
How to click on an element with an unique attribute using Selenium

Time:04-09

The website has multiple turn off buttons and the only thing that differentiates between them is the sales_area_uid 257207. How can I code this to click on the value of the uid?

HTML Source:

<input type="submit"  name="submit_sales_area_status" data-sales-area-uid="275207" data-value="0" value="Turn Off">

Code so far:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Chrome(r'/usr/bin/chromedriver')
driver.get("https://izoneapps.zonalconnect.com/mobile_manager/login.php")

driver.implicitly_wait(7)

driver.find_element_by_id("username").send_keys('*****')
driver.find_element_by_id("password").send_keys('*****')

driver.find_element_by_name("submit_login").click()

driver.get("https://izoneapps.zonalconnect.com/mobile_manager/ordering/")

driver.find_elements_by_xpath ("//div[@data-sales-area-uid=275207]").click()

CodePudding user response:

driver.find_element_by_xpath("//input[@data-sales-area-uid='275207']").click()

This should work for your problem

CodePudding user response:

The value of the data-sales-area-uid attribute seems dynamic. Now among the several Turn Off elements if the desired element is always assigned the same value of data-sales-area-uid i.e. 275207 then to click on the specific element you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following locator strategies:

  • Using CSS_SELECTOR:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input.button.delete.sales-area-status[data-sales-area-uid='275207']"))).click()
    
  • Using XPATH:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@class='button delete sales-area-status' and @data-sales-area-uid='275207']"))).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
    
  • Related