[英]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.