我写了这个布尔方法,但我想让它更短、更智能,因为有3行相同的XPath
。有人能帮我吗?感谢
public boolean VerifyKORSecDispaly() {
boolean a = driver
.findElement(By
.xpath("(//tr[@data-testid='row']//td[@class='kor'])[1]//span[@class='da']"))
.getText().contains("d");
boolean b = driver
.findElement(By
.xpath("(//tr[@data-testid='row']//td[@class='kor'])[2]//span[@class='da']"))
.getText().contains("d");
boolean c = driver
.findElement(By
.xpath("(//tr[@data-testid='row']//td[@class='kor'])[3]//span[@class='da']"))
.getText().contains("d");
if (a == true && b == true && c == true) {
return true;
} else {
return false;
}
}
您可以使用List<>
,因为您在xpath中使用索引。
//tr[@data-testid='row']//td[@class='kor']
<-该选择器将返回多个元素
基于这些元素,我们可以找到span[@class='da']
元素。
代码:
public boolean VerifyKORSecDispaly() {
boolean a = doesRowTextContain(0, "d");
boolean b = doesRowTextContain(1, "d");
boolean c = doesRowTextContain(2, "d");
if (a == true && b == true && c == true) {
return true;
} else {
return false;
}
}
private boolean doesRowTextContain(int index, String expectedString) {
By spanSelector = By.xpath(".//span[@class='da']"); //the dot . reduces the scope of the element. Instead of searching through all the elements in source, we'll reduce the scope to parent element
List<WebElement> dataRows = driver.findElements(By.xpath("//tr[@data-testid='row']//td[@class='kor']"));
return dataRows.get(index).findElement(spanSelector).getText().contains(expectedString);
}
还有一件事是,您不必将a, b or c
和true
进行比较,因为它是if
语句中的默认期望值。
if (a && b && c) {
return true;
} else {
return false;
}
甚至
return a && b && c
:(
最后的方法可能是这样的:
public boolean VerifyKORSecDispaly() {
return doesRowTextContain(0, "d") && doesRowTextContain(1, "d") && doesRowTextContain(2, "d");
}
private boolean doesRowTextContain(int index, String expectedString) {
By spanSelector = By.xpath(".//span[@class='da']"); //the dot . reduces the scope of the element. Instead of searching through all the elements in source, we'll reduce the scope to parent element
List<WebElement> dataRows = driver.findElements(By.xpath("//tr[@data-testid='row']//td[@class='kor']"));
return dataRows.get(index).findElement(spanSelector).getText().contains(expectedString);
}