[英]Extract text from multiple xpath and assert text - Selenium/Java
我需要在元素中找到文本並斷言它是否與所需的結果匹配。
事實是,頁面中1-100個元素之間可以有n個元素。 因此,我無法獲取所有這些元素的xpath,然后在其中聲明文本。
xpath看起來像這樣:(從第一個元素開始)
(//DIV[@class='issues-list-item clearfix'])[1]
(//DIV[@class='issues-list-item clearfix'])[2]
(//DIV[@class='issues-list-item clearfix'])[3]
(//DIV[@class='issues-list-item clearfix'])[4]
....
(//DIV[@class='issues-list-item clearfix'])[100]
如何遍歷這些xpath並為我的文本斷言?
在參考了幾篇文章之后,我嘗試了以下方法,但實際上並沒有幫助。
private static WebElement element = null;
private static List<WebElement> elements = null;
public WebElement test() throws Exception {
elements = driver.findElements(By.xpath("(//DIV[@class='issues-list-item clearfix'])[1]"));
for (WebElement element : elements) {
List<WebElement> TE = element.findElements(By.xpath("(//DIV[@class='issues-list-item clearfix'])[1]"));
if (TE.size() > 0) {
String myText = TE.get(0).getText();
if (myText.contains("High")) {
return element;
}
}
}
return null;
您可以嘗試以下方法:
public List<WebElement> test() throws Exception {
List<WebElement> TE = new ArrayList<WebElement>();
elements = driver.findElements(By.xpath("(//DIV[@class='issues-list-item clearfix'])"));
for (WebElement element : elements) {
if(element.getText().contains("High")) {
TE.add(element);
}
}
return TE;
}
請注意,它將返回一個列表Web元素,其中包含High
作為文本。
更有效的方法是將“高”的支票添加到定位器。 這樣,您不必遍歷所有元素即可僅查找所需元素。 定位器可以為您更快地完成所有工作。 代碼也少了很多。
public List<WebElement> test() throws Exception {
return driver.findElements(By.xpath("(//DIV[@class='issues-list-item clearfix'][contains(.,'High')])"));
}
您可以通過多種方法來驗證是否找到了所需的元素。 一種方法是使用類似的TestNG Assert
Assert.assertTrue(test().size() > 0, "Verify an element containing 'High' was found.");
//DIV[@class='issues-list-item clearfix'])[1]
您的查詢錯誤。 最后的[1]表示它將從之前所有與查詢匹配的項目中選擇第一個項目,也就是您只會與第一個進行比較。 您不需要的第二個查詢,如果要檢查大小,則忽略if(可選在for循環之前)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.