[英]Selenium WebDriver : Login Script not working
我正在尝试创建一个登录脚本,在该脚本中我将尝试验证登录是否成功,但是会引发NoSuchElementException。任何输入来更正脚本将非常有帮助。
下面是我从中调用Login方法的Page类:
package abhi;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.By;
public class PageClass
{
//Declare the WebDriver
WebDriver driver;
//Declare the Login Page Elements
By Username = By.name("username");
By Password = By.name("password");
By LoginButton = By.className("ui-button-text");
By OnlineCatalog = By.linkText("Online Catalog");
By ErrorMessage = By.className("messageStackError");
//Create the constructor with the same name as that of the Page Class
public PageClass (WebDriver driver)
{
this.driver=driver;
}
//Create Login Method
public void Login (String Uname, String Pwd)
{
driver.findElement(Username).sendKeys(Uname);
driver.findElement(Password).sendKeys(Pwd);
driver.findElement(LoginButton).click();
}
}
下面是测试脚本来验证我在使用以下验证的登录名:
1)如果注销链接可用,则打印“登录成功” 2)如果显示错误消息,则打印“登录失败”但是,当我输入无效的凭据时,它不会通过进入“否则”来读取错误消息,并且仍然一直在寻找Logoff链接,因此抛出NoSuchElementException。下面是测试脚本:
package abhi;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver
public class TestCaseClass
{
public static WebDriver driver;
public static void main(String[] args) throws InterruptedException
{
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\k746261\\Desktop\\Selenium\\chromedriver.exe");
driver = new ChromeDriver();
PageClass object = new PageClass (driver);
driver.get("http://www.gcrit.com/build3/admin/login.php");
object.Login("admin1", "admin@123");
Thread.sleep(3000);
if ((driver.findElement(By.linkText("Logoff")).isDisplayed()))
{
System.out.println("Login Successfull");
}
else if (((driver.findElement(By.linkText("Logoff")).isDisplayed()==false))
|| ((driver.findElement(By.tagName("td")).isDisplayed())))
{
System.out.println("Login Failed");
}
driver.close();
}
}
您的代码会引发NoSuchElementException,因为它无法在页面上找到注销链接。您应该在try{} catch{}
检查元素是否显示的地方用try{} catch{}
块包装代码。 try{} catch{}
像这样修改并查看是否有帮助:
Boolean elementvisible ;
try
{
driver.findElement(By.linkText("Logoff"));
elementvisible = true;
}
catch (NoSuchElementException e) {
// TODO: handle exception
System.out.println("Element not found : " + e);
elementvisible = false;
}
if (elementvisible == true)
{
System.out.println("Login Successfull");
}
else if ((elementvisible == false) || (driver.findElement(By.tagName("td")).isDisplayed()))
{
System.out.println("Login Failed");
}
注意:如果测试用例成功(成功登录),则可以添加WebDriverWait wait
以等待链接可见。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.