1

I've been trying to click a button using selenium package in python. I've been having trouble figuring out how to identify the button, though. After way too much time, I tried manually copying the xpath from the javascript console, but get a NoSuchElementException when I try to call driver.find_element_from_xpath('<xpath>').

I'm really not sure how that's possible. The HTML is extremely long - what I'm ultimately trying to locate is nested under multiple table, body, td, tr tags. Here's the element though:

<a href="Javascript:void" onclick="javascript:toggleDisplay(this, trAK);return false;">Alaska</a>

When I clicked "Copy Xpath" in Chrome, it returned this string: //*[@id="Form1"]/table/tbody/tr[3]/td/table/tbody/tr[1]/td/table/tbody/tr/td/table/tbody/tr[2]/td/table/tbody/tr[5]/td/table/tbody/tr[3]/td/table[1]/tbody/tr[1]/td[2]/a

I'm pretty new to this so can anyone help me understand why this won't work and/or what I could do to fix it?

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
jonpie
  • 31
  • 6

1 Answers1

1

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 Locator Strategies:

  • Using LINK_TEXT:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.LINK_TEXT, "Alaska"))).click()
    
  • Using (logical) XPATH (instead of absolute xpath):

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[contains(@onclick, 'toggleDisplay') and text()='Alaska']"))).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
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
  • 1
    Awesome! I did not realize a JavaScript element would have to be called like that. I have almost 0 knowledge of html or js. This explains things and got my stuff working! I am curious how you were able to locate that element so easily? I tried so many `driver.find_element_by...` calls and the Alaska string never did it for me – jonpie Jul 31 '19 at 20:34