1

我已经编写了代码来验证没有定位器的文本和可见性。请各位大侠指教,这是正确的方法吗?

如果有任何替代方法,那么您的建议将不胜感激。

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();

}

}
4

1 回答 1

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();

}

}
于 2013-06-20T06:56:15.953 回答