Eilon123
Eilon123

Reputation: 1

Clicking on HTML <a> tag with selenium python

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

Answers (2)

undetected Selenium
undetected Selenium

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

Dmitri T
Dmitri T

Reputation: 168237

  1. Make sure that the element doesn't belong to the iframe, if this is the case - you will need to switch_to_frame first
  2. Make sure that the element doesn't belong to the Shadow DOM, if this is the case - you will have to find the relevant ShadowRoot and locate your element relatively
  3. 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

Related Questions