Reputation: 31
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?
Upvotes: 1
Views: 831
Reputation: 193088
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
Upvotes: 1