I am trying to click a button on a website in Python using Selenium. The html looks like this:
<a class="btn btn-default btn-lg primary-light-blue-btn" 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. Eg:
l = driver.find_element(By.XPATH, "//button[text()='Create report']")
I have also tried introducing a wait, but that does not help, eg:
l = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//button[text()='Create report']")))
change the tag //button
to //a
:
l = driver.find_element(By.XPATH, "//a[@class='btn btn-default btn-lg primary-light-blue-btn']")
As per the given HTML:
<a class="btn btn-default btn-lg primary-light-blue-btn" onclick="createReport()">Create report</a>
The element is a <a>
tag.
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
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.