Home > Software design >  How to automate elements without a class id in python selenium?
How to automate elements without a class id in python selenium?

Time:12-27

I'm trying to automate the pressing of the following button in selenium, but I'm used to referring to elements using their ID. This button has no ID:

<button type="button"  ng-transclude="" 
en-tap="AssignDateTime();showModal('utilities/assignment 
editior/delete',{item:item}, assignmentslist.refresh)" style="touch- 
action: manipulation; user-select: none; -webkit-user-drag: none; - 
webkit-tap-highlight-color: rgba(0, 0, 0, 0);">

<en-icon icon="trash" >
</en-icon>
</button>

CodePudding user response:

Most elements have no ID attribute.
The most widely used approach is to locate web elements by CSS_SELECTOR or by XPATH.
Try locating this specific element by CSS_SELECTOR

"button.button-error.en-button"

Or by XPATH

"//button[@class='button-error en-button']"

CodePudding user response:

You can use just class:

driver.find_element_by_class_name('button-error').click() or driver.find_element_by_class_name('en-button').click()

or

if you find multiple elements with same class name then use xpath

//button[@class='button-error en-button'] or (//button[@class='button-error en-button'])[1]

CodePudding user response:

To click() on the element you can use either of the following Locator Strategies:

  • Using css_selector:

    driver.find_element(By.CSS_SELECTOR, "button.button-error.en-button[en-tap^='AssignDateTime'][en-tap*='assignmentslist']").click()
    
  • Using xpath:

    driver.find_element(By.XPATH, "//button[@class='button-error en-button' and starts-with(@en-tap, 'AssignDateTime')][contains(@en-tap, 'assignmentslist')]").click()
    

The desired element is a dynamic element, so to click on the 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, "button.button-error.en-button[en-tap^='AssignDateTime'][en-tap*='assignmentslist']"))).click()
    
  • Using XPATH:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@class='button-error en-button' and starts-with(@en-tap, 'AssignDateTime')][contains(@en-tap, 'assignmentslist')]"))).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