在页面上查找具有动态位置的元素的XPath(直接跳转到元素?)

时间:2018-03-16 16:38:54

标签: javascript selenium xpath

我正在尝试编写Selenium测试,以便在数据库频繁更改时经常重新加载警报。这些提醒位于<ul> <li>,并且<h4>下方的<li>元素都有唯一标题(在此之上有很多div)。

它看起来像是:

<h4 title="Title" class="message-title alarm-list-name ng-binding">Displayed Value matches Title Value</h4>

当我使用Chrome的“复制XPath”功能时,我会获得//*[@id=": 0"]/a/div[2]/h5[1]之类的路径,但当然每次页面重新加载时都会发生变化(当我使用此页面时,我仍然会“找不到元素”) 。我想知道是否有办法直接跳到具有特定值的<h4>,因为这是处理这个问题最简单的方法,我想。我已经尝试了//h4[@title="Title"],但我找不到元素。

我也尝试了driver.findElement(By.linkText("Text"));类似的结果。我倾向于认为xpath会更好,因为它似乎更通用。

如果您有其他Selenium建议,如果您可以在javascript中使用jmeter的webdriver插件演示它,我将不胜感激,因为这是我一直在使用的工具。

1 个答案:

答案 0 :(得分:1)

更多信息可以帮助我们解决您的查询是否要提取文本显示的值匹配标题值,或者您想要在其上调用任何方法。

但是,根据 HTML ,您已共享 WebElement Angular Element ,因此您需要诱导 WebDriverWait 使用正确的 ExpectedConditions ,如下所示( Java Solution ):

  • 提取文字显示的值与标题值匹配

    new WebDriverWait(driver, 20).until(ExpectedConditions.textToBePresentInElementLocated(By.xpath("//h4[@class='message-title alarm-list-name ng-binding' and @title='Title']"), "Displayed Value matches Title Value"));
    System.out.println(driver.findElement(By.xpath("//h4[@class='message-title alarm-list-name ng-binding' and @title='Title']")).getAttribute("innerHTML"));