简体   繁体   中英

Copy xpath Doesn't Provide Correct xpath?

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?

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 

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM