我编写了代码来验证文本和可见性WITHOUT定位器。请建议大家,这是正确的方法吗?
如果有其他替代方法,那么您的建议表示赞赏。
public class TextVisibility {
WebDriver driver = new FirefoxDriver();
public static String baseUrl = "website url";
public String client = "your search string";
public void visibilityOfText(){
driver.get(baseUrl);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
WebElement element = driver.findElement(By.cssSelector("body"));
boolean feedBack = driver.findElement(By.cssSelector("body")).getText().contains(client);
boolean feedbackVisible = element.isDisplayed();
if(feedBack==true){
System.out.println(client+ "is present");
if(feedbackVisible==true){
System.out.println(client+ "is visible");
}
else{
System.out.println(client+ "is not visible");
}
}
else{
System.out.println(client+ "is not present");
}
driver.close();
driver.quit();
}
}
答案 0 :(得分:2)
我会做得更好一点。我将跳过质疑你为什么要这样做并假设你只需要这样做。
因此。这个缺陷就在这一行:
boolean feedBack = driver.findElement(By.cssSelector("body")).getText().contains(client);
因为理论上文字可能不在页面上,然后你会得到NoSuchElementException
更好的方法是
//skipping initialization part
try{
boolean feedBack = driver.findElement(By.cssSelector("body")).getText().contains(client);
boolean feedbackVisible = element.isDisplayed();
} catch (NoSuchElementException e){
boolean feedback = false;
boolean feedbackVisible = false;
}
if(feedBack==true){
System.out.println(client+ "is present");
if(feedbackVisible==true){
System.out.println(client+ "is visible");
}
else{
System.out.println(client+ "is not visible");
}
}
else{
System.out.println(client+ "is not present");
}
driver.close();
driver.quit();
}
}