Home > Back-end >  Selenium can't find button
Selenium can't find button

Time:01-30

I am trying to click a button on a website in Python using Selenium. The html looks like this:

<a  onclick="createReport()">Create report</a>

I have tried using:

l = driver.find_element(By.XPATH, "//button[@class='btn btn-default btn-lg primary-light-blue-btn']")

But I get the error:

NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//button[@class='btn btn-default btn-lg primary-light-blue-btn']"}

I have also tried other things, but it just won't find the button. E.g.:

l = driver.find_element(By.XPATH, "//button[text()='Create report']")

I have also tried introducing a wait, but that does not help, e.g.:

l = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//button[text()='Create report']")))

CodePudding user response:

change the tag //button to //a:

l = driver.find_element(By.XPATH, "//a[@class='btn btn-default btn-lg primary-light-blue-btn']")

CodePudding user response:

As per the given HTML:

<a  onclick="createReport()">Create report</a>

The element is a <a> tag.


Solution

To click on the element with text as Create report you can use either of the following locator strategies:

  • Using link_text:

    driver.find_element(By.LINK_TEXT, "Create report").click()
    
  • Using css_selector:

    driver.find_element(By.CSS_SELECTOR, "a.btn.btn-default.btn-lg.primary-light-blue-btn[onclick^='createReport']").click()
    
  • Using xpath:

    driver.find_element(By.XPATH, "//a[@class='btn btn-default btn-lg primary-light-blue-btn' and starts-with(@onclick, 'createReport')]").click()
    

Ideally to click on the clickable element you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following locator strategies:

  • Using LINK_TEXT:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.LINK_TEXT, "Create report"))).click()
    
  • Using CSS_SELECTOR:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a.btn.btn-default.btn-lg.primary-light-blue-btn[onclick^='createReport']"))).click()
    
  • Using XPATH:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[@class='btn btn-default btn-lg primary-light-blue-btn' and starts-with(@onclick, 'createReport')]"))).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