简体   繁体   English

按钮的Xpath,文本为“新”

[英]Xpath for button having text as 'New'

In our application almost in every screen we have a button with text 'New', Here is the html source for one of the button: 在我们的应用程序中,几乎在每个屏幕中我们都有一个带有文本“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>

I have tried using the below statement to click on the button: 我尝试使用以下语句单击按钮:

driver.findElement(By.xpath("//button[[@type, 'submit'] and [text()='New']]")).click();

But this was not working 但这不起作用

org.openqa.selenium.InvalidSelectorException: The given selector //button[[@type= 'submit'] and [text()='New']] is either invalid or does not result in a WebElement.

Currently I am using the below code to click on the button: 目前我使用以下代码点击按钮:

List<WebElement> allButt = driver.findElements(By.tagName("button"));
for (WebElement w : allButt)
{
    if (w.getText().matches("New"))
    {
        w.click();
        break;
    }
}

As I have almost 150 buttons in the page. 因为我在页面中有近150个按钮。 Is there any other way? 还有其他方法吗?

Your xpath syntax is wrong - you don't need the inner set of square brackets - but even if you fix this: 您的xpath语法错误 - 您不需要内部方括号 - 但即使您修复此问题:

//button[@type, 'submit' and text()='New']

it won't select what you want it to. 它不会选择你想要的东西。 The problem is that the "New" is not text contained directly in the button element but is inside a child span element. 问题是“新”不是直接包含在按钮元素中的文本,而是在子span元素内。 If instead of text() you just use . 如果不是text()你只需使用. then you can check the whole string value of the element (the concatenation of all descendant text nodes at whatever level) 然后你可以检查元素的整个字符串值(所有后代文本节点在任何级别的串联)

//button[@type='submit' and contains(., 'New')]

Or check span instead of text() : 或者检查span而不是text()

//button[@type='submit' and span='New']

(submit buttons containing a span whose value is "New") (提交包含值为“新”的跨度的按钮)

Try this xpath instead: 请尝试使用此xpath:

//button[@type='submit']/span[.='New']

Demo 演示

http://www.xpathtester.com/xpath/ff393b48183ee3f373d4ca5f539bedf2 http://www.xpathtester.com/xpath/ff393b48183ee3f373d4ca5f539bedf2


EDIT 编辑

Following comment from @Ian Roberts , you can use the following xpath expression instead if the click on the button element is important: 根据@Ian Roberts的评论,如果点击按钮元素很重要,您可以使用以下xpath表达式:

//button[@type='submit']/span[.='New']/..

The very simple solution for the above issue is to use span with option contains(text(),''). 上述问题的一个非常简单的解决方案是使用span with option contains(text(),'')。

You can use the following xpath code 您可以使用以下xpath代码

//span[contains(text(),'New')] //跨度[包含(文本(), '新')]

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

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