简体   繁体   English

找不到元素-xPath正确

[英]Can't find element - xPath correct

So, I have an XPath (I've verified this works and has 1 unique value via Google Chrome Tools. 因此,我有一个XPath(我已经通过Google Chrome浏览器工具验证了此功能并具有1个唯一的值。

I've tried various methods to try and get this xpath, initally using right click > copy xpath in chrome gave me: 我尝试了各种方法来尝试获取此xpath,最初使用right click > copy xpath在chrome中right click > copy xpath给了我:

//*[@id="hdr_f0f7cdb71b9a3f44782b87386e4bcb3e"]/th[2]/span/a

However, this ID changes on every reload. 但是,此ID在每次重新加载时都会更改。

So, i eventually got it down to: 因此,我最终将其归结为:

//th[@name="name"]/span/a/text()

element = driver.find_element_by_xpath("//th[@name='name']/span/a/text()")
print(element)


selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//th[@name='name']/span/a/text()"}

check this: 检查一下:

len(driver.find_elements_by_xpath('//*[contains(@id, "hdr_")]'))

if you won't get a lot of elements you're done with this: 如果您不会得到很多元素,则可以完成以下操作:

driver.find_elements_by_xpath('//*[contains(@id, "hdr_")]')

You should not be using /text() for a WebElement. 您不应将/ text()用于WebElement。 Use "//th[@name='name']/span/a" as the Xpath and print the text using element.text (Not sure about the exact method for Python, but in Java it is element.getText() ) 使用“ // th [@ name ='name'] / span / a”作为Xpath并使用element.text打印文本(不确定Python的确切方法,但在Java中是element.getText())

I will suggest using absolute XPath rather than relative XPath it might resolve it if the id is changing with every load. 我会建议使用绝对XPath而不是相对XPath,如果id随每次加载而变化,它可能会解决它。 please see below how absolute XPath is different from relative using the google search bar. 请在下面使用Google搜索栏查看绝对XPath与相对XPath有何不同。

  • Relative XPath - //*[@id="tsf"]/div[2]/div/div[1]/div/div[1]/input 相对XPath-// * [@@ id =“ tsf”] / div [2] / div / div [1] / div / div [1] / input
  • absolute XPath - /html/body/div/div[3]/form/div[2]/div/div[1]/div/div[1]/input 绝对XPath-/ html / body / div / div [3] / form / div [2] / div / div [1] / div / div [1] / input

I understand as you said you cannot share a link but people here can help if you can share inspect element snapshot showing DOM. 我理解您所说的无法共享链接,但是如果您可以共享显示DOM的检查元素快照,那么这里的人可以为您提供帮助。 so that if there is an issue in XPath it can be rectified. 因此,如果XPath中存在问题,则可以将其纠正。 Thanks :-) 谢谢 :-)

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

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