以下代码表示"方法text()未定义类型Test"并提示我在Test。类中创建一个新的函数text()。
driver.findElement(By.xpath(contains(text(), "menu")));
我正在使用Eclipse Kepler和Selenium 2.39.0。
我收到的例外是:org.openqa.selenium.NoSuchElementException
。
我无法弄清楚我哪里出错了。
答案 0 :(得分:2)
XPath
表达式需要用引号括起来 - 因为您尝试解析的表达式也包含字符串文字,我建议您将文字切换为单撇号'
。此外,除非您希望根元素包含文本menu
,否则您需要更具体地了解要搜索的元素。例如,以下xpath:
driver.findElement(By.xpath("//*[contains(text(), 'menu')]"));
将找到带有文本“menu”的li
元素(注意xpath区分大小写):
<html>
<foo>
<bar>
<ul>
<li id="123">menu</li>
</ul>
</bar>
</foo>
</html>
如果可能的话,更加确定,例如如果您知道它是li
元素:
driver.findElement(By.xpath("//li[contains(text(), 'menu')]"));
修改(OP将实际 html打开)
这将找到DIV
元素:
driver.findElement(By.xpath("//DIV[@style[contains(., 'menubar_menubutton.png')]]"));
请注意,xpath区分大小写 - 因此您需要复制SHOUTCASE标记。
答案 1 :(得分:1)
我觉得有一种更简单的方法可以做到这一点。
我个人只是这样做:
WebElement we = driver.findElement(By.Id("123"))
或者如果你想利用css选择器,你可以这样做:
WebElement we = driver.findElement(By.cssSelector("li:nth-child(1)")) //baring you know the index of the list