简体   繁体   English

复制xpath不能提供正确的xpath?

[英]Copy xpath Doesn't Provide Correct xpath?

I've been trying to click a button using selenium package in python. 我一直在尝试使用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>') . 经过太多时间后,我尝试从javascript控制台手动复制xpath ,但是在尝试调用driver.find_element_from_xpath('<xpath>')时收到NoSuchElementException

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. HTML非常长-我最终试图定位的内容嵌套在多个表,正文,td,tr标签下。 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 当我在Chrome中点击“复制Xpath”时,它返回了以下字符串: //*[@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 : 所需的元素是启用JavaScript的元素,因此要对元素click()就必须为element_to_be_clickable()诱导WebDriverWait ,并且可以使用以下两种定位器策略之一

  • Using LINK_TEXT : 使用LINK_TEXT

     WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.LINK_TEXT, "Alaska"))).click() 
  • Using (logical) XPATH (instead of absolute xpath): 使用(逻辑) XPATH (而不是绝对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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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