如何使用Selenium-Webdriver和Java验证html5约束验证消息

时间:2019-03-22 20:11:42

标签: java html5 selenium-webdriver webdriverwait constraint-validation

如何验证以下消息?必需的类具有浮动消息。:

尝试以下操作,但出现错误“没有此类警报”

package firsttestngpackage;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.annotations.Test;

public class LoginBambu {

public String baseUrl = "http://132.148.19.159:8086/panel/#/login";
String driverPath = "H:\\chromedriver.exe";
public WebDriver driver;    

@Test
public void IniciarSesion() {
System.setProperty("webdriver.chrome.driver", driverPath);
driver = new ChromeDriver();
driver.get(baseUrl);

WebElement login = driver.findElement(By.cssSelector("#page-top > div.margen-panel-60.ng-scope > div > div.row.container-fluid.ng-scope > div:nth-child(1) > div > form > button"));
  login.click();

  String mensaje=driver.switchTo().alert().getText();
  System.out.println(mensaje);    
}
}

1 个答案:

答案 0 :(得分:0)

HTML5约束验证消息是Constraint API's element.setCustomValidity()方法的结果。

  

注意:HTML5约束验证不会消除服务器端验证的需要。即使可以预期的无效表单请求的数量要少得多,无效请求仍然可以由不兼容的浏览器(例如,没有HTML5和JavaScript的浏览器)或试图欺骗您的Web应用程序的坏人发送。因此,与HTML4一样,您还需要在服务器端验证输入约束,方法与在客户端进行的验证一致。

解决方案

要检索从element.setCustomValidity()方法得到的文本,可以使用以下解决方案:

  • 代码块:

    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.chrome.ChromeDriver;
    import org.openqa.selenium.chrome.ChromeOptions;
    import org.openqa.selenium.support.ui.ExpectedConditions;
    import org.openqa.selenium.support.ui.WebDriverWait;
    
    public class validationmessage {
    
        public static void main(String[] args) {
    
            System.setProperty("webdriver.chrome.driver", "C:\\Utility\\BrowserDrivers\\chromedriver.exe");
            ChromeOptions options = new ChromeOptions();
            options.addArguments("start-maximized");
            options.addArguments("disable-infobars");
            options.addArguments("--disable-extensions"); 
            WebDriver driver =  new ChromeDriver(options);
            driver.get("http://132.148.19.159:8086/panel/#/login");
            WebElement username = new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("input.form-control.ng-pristine.ng-invalid.ng-invalid-required.ng-touched[placeholder='Usuario']")));
            System.out.println(username.getAttribute("validationMessage"));
        }
    }
    
  • 控制台输出:

    Please fill out this field.