java中的Selenium消息错误和消息成功



我遇到了一个查找不存在的元素的问题。当我尝试登录到应用程序时,如果登录失败,它将显示元素-

dr.findElement(By.className("message-error ")).getText();

成功登录后,它将显示以下内容:

dr.findElement(By.className("message-success")).getText();

当我运行代码但它找不到元素时,执行就会停止,出现异常:element is not found

String mes=null;        
mes=dr.findElement(By.className("message-success")).getText();
if(mes!=null) {
File out= new File("success.txt");
FileWriter fr =new FileWriter(out,true);
PrintWriter pw=new PrintWriter(fr);
pw.println(mes+"|"+user.get(i)+"|"+pass.get(i));
pw.close();
}

mes=dr.findElement(By.className("message-error")).getText();
if(mes!=null) {
File out= new File("error.txt");
FileWriter fr =new FileWriter(out,true);
PrintWriter pw=new PrintWriter(fr);
pw.println(mes+"|"+user.get(i)+"|"+pass.get(i));
pw.close();
}

元素未出现。

例如,成功元素在成功之前不会显示,错误元素在出现错误之前不会出现在CSS中。

那个么,我该如何判断元素是应该退出,还是应该活起来,或者出现在做一个动作上呢?

如果登录成功,在if语句中应该做什么?这个和登录失败了吗?

使用WebdriverWait等待成功消息的可见性,

// After  valid login 
WebDriverWait wait = new WebDriverWait(driver, 60);
WebElement successmessage wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("message-success")));
sucessmessage.getText();

类似地,对于错误消息,

// After  invalid login
WebElement errormessage wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("message-error")));
errormessage.getText();

我认为您有相同的元素,但类会根据应用程序的行为而变化。假设您能够登录到应用程序中,那么它会显示具有属性message-success的类的message元素,如果不允许,那么在同一元素中显示具有属性'message-error'的类的error消息。

我在下面的代码中处理了同样的问题

// first get the message element with some other locator or other attribute (don't use class name)
WebElement message = driver.findElement(By.locator);
if(message.getAttribute("class").contains("message-success")){
System.out.println("Success message is " + message.getText())        
// write the code to perform further action you want on login success
}else if (message.getAttribute("class").contains("message-error")){
System.out.println("Error message is " + message.getText())  
// write the code to perform further action you want on login Fail
}else{
System.out.println("Message is empty" + message.getText())
}

如果您有进一步的疑问,请告诉我。

我的选择是使用Webdriver wait。这是找到元素的最佳方法。

public WebDriverWait(WebDriver driver,15)
WebElement successmessage = wait.until(ExpectedConditions.visibilityOfallElementLocatedby(By.className("message-success")));
sucessmessage.getText();

定位的所有元素的可见性

检查网页上与定位器匹配的所有元素是否可见的期望。可见性意味着图元不仅显示,而且高度和宽度都大于0。

上面我写的是成功消息,类似的方式尝试无效登录。

要使用不同类型的等待,请检查此文档-https://seleniumhq.github.io/selenium/docs/api/java/allclasses-noframe.html

search在该文档中等待。

这是它与我一起工作的问题的答案

try {
WebElement sucmes=dr.findElement(By.xpath("//div[@class='message']"));
String suclogin="login success:";
if(sucmes.getText().contains(suclogin)) {
File suclogin= new File("suclog.txt");
FileWriter suclogr =new FileWriter(suclogin,true);
PrintWriter suclogrw=new PrintWriter(suclogr);
suclogrw.println(sucmes.getText());
suclogrw.close();
}else{
//the other action here 
}
}

最新更新