如何检查用户名是否有效

How to check the username is valid

实际上我尝试检查登录页面中的用户名和密码是否正确。 所以我写了关于登录的代码。当注销按钮可见时检查用户是否有效。

但是我的声明不起作用

driver.findElement(By.id("username")).sendKeys(sUsername);
driver.findElement(By.id("password")).sendKeys(sPassword);
driver.findElement(By.name("login")).click();


boolean logvisibile = driver.findElement(By.xpath(".//*[@id='account']/ul/li[2]/a")).isDisplayed();


Thread.sleep(1000);

if(logvisibile == true)

{
System.out.println("Succesfull");

}else

{
System.out.println("Failed");

}
}

**输出:

FAILED: test(“testuser_1″, “Test@123″) org.openqa.selenium.NoSuchElementException: Unable to locate element: {“method”:”xpath”,”selector”:”.//*[@id=’account’]/ul/li[2]/a”} Command duration or timeout: 10.06 seconds For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html**

我认为您甚至在单击“登录”之前就在检查“注销”按钮的可见性。 (假设 //*[@id='account']/ul/li[2]/a 是您的注销按钮)

boolean logvisibile = driver.findElement(By.xpath(".//*[@id='account']/ul/li[2]/a")).isDisplayed();
driver.findElement(By.name("login")).click();

先点击登录,然后查看可见性。

driver.findElement(By.name("login")).click();
boolean logvisibile = driver.findElement(By.xpath(".//*[@id='account']/ul/li[2]/a")).isDisplayed();

也不需要这样做 - if(logvisibile == true) 你可以简单地做 if(logvisible)

编辑:检查此解决方案的登录方案,工作得很好。

    public static void main(String[] args) {

    driver = new FirefoxDriver();
    driver.navigate().to("http://newtours.demoaut.com/mercurysignon.php");

    WebElement username = driver.findElement(By.cssSelector("input[name='userName']"));
    username.sendKeys("dharam111");

    WebElement password = driver.findElement(By.cssSelector("input[name='password']"));
    password.sendKeys("password");

    WebElement loginBtn = driver.findElement(By.cssSelector("input[name='login']"));
    loginBtn.click();

    List<WebElement> objLogOutLink = driver.findElements(By.cssSelector("a[href*='signoff']"));
    if(objLogOutLink.size() > 0){
        if(objLogOutLink.get(0).getText().contains("SIGN-OFF")){
            System.out.println("Login successful...Success");
        }
    }
    else{
        System.out.println("Login Failed.");
    }

}