Reputation: 1
I try to click on html a tag with selenium but I get an error.
How can I get selenium to click on such tag?
I've tried this code but I get an error:
driver.find_element_by_id("btnCreateJE").click()
HTML code:
<a id="btnCreateJE" data-permission="true" onclick="NewManualJE()" href="@" class="btn waves-effect waves-light"> New </a>
Python selenium code:
driver.find_element_by_id("btnCreateJE").click()
I get that error:
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[id="btnCreateJE"]"}
(Session info: chrome=75.0.3770.142)
Upvotes: 0
Views: 93
Reputation: 193388
The desired element is a JavaScript enabled element so to click()
on the element you have to induce WebDriverWait for the element to be clickable and you can use either of the following solutions:
Using PARTIAL_LINK_TEXT
:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.PARTIAL_LINK_TEXT, "New"))).click()
Using CSS_SELECTOR
:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a.btn.waves-effect.waves-light#btnCreateJE[onclick^='NewManualJE']"))).click()
Using XPATH
:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[@class='btn waves-effect waves-light' and @id='btnCreateJE'][starts-with(@onclick, 'NewManualJE')]"))).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
Upvotes: 2
Reputation: 168237
It might be the case the link is not immediately present in DOM, i.e. it's being added later as a result of an AJAX call. If this is the case - consider adding Explicit Wait like:
WebDriverWait(driver, 10).until(expected_conditions.presence_of_element_located((By.ID, "btnCreateJE"))).click()
Upvotes: 2