[英]Xpath for button having text as 'New'
在我们的应用程序中,几乎在每个屏幕中我们都有一个带有文本“New”的按钮,这是其中一个按钮的html源:
<button id="defaultOverviewTable:j_id54" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only ui-state-hover" type="submit" name="defaultOverviewTable:j_id54" role="button" aria-disabled="false">
<span class="ui-button-text ui-c">New</span>
</button>
我尝试使用以下语句单击按钮:
driver.findElement(By.xpath("//button[[@type, 'submit'] and [text()='New']]")).click();
但这不起作用
org.openqa.selenium.InvalidSelectorException: The given selector //button[[@type= 'submit'] and [text()='New']] is either invalid or does not result in a WebElement.
目前我使用以下代码点击按钮:
List<WebElement> allButt = driver.findElements(By.tagName("button"));
for (WebElement w : allButt)
{
if (w.getText().matches("New"))
{
w.click();
break;
}
}
因为我在页面中有近150个按钮。 还有其他方法吗?
您的xpath语法错误 - 您不需要内部方括号 - 但即使您修复此问题:
//button[@type, 'submit' and text()='New']
它不会选择你想要的东西。 问题是“新”不是直接包含在按钮元素中的文本,而是在子span元素内。 如果不是text()
你只需使用.
然后你可以检查元素的整个字符串值(所有后代文本节点在任何级别的串联)
//button[@type='submit' and contains(., 'New')]
或者检查span
而不是text()
:
//button[@type='submit' and span='New']
(提交包含值为“新”的跨度的按钮)
请尝试使用此xpath:
//button[@type='submit']/span[.='New']
演示
http://www.xpathtester.com/xpath/ff393b48183ee3f373d4ca5f539bedf2
编辑
根据@Ian Roberts的评论,如果点击按钮元素很重要,您可以使用以下xpath表达式:
//button[@type='submit']/span[.='New']/..
上述问题的一个非常简单的解决方案是使用span with option contains(text(),'')。
您可以使用以下xpath代码
//跨度[包含(文本(), '新')]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.