昨天写一个selenium+java的登录脚本,输入完成用户名、密码后点击登录,登录到首页后验证欢迎语是否正确,但是就是获取不到页面元素,一直报错,换了很多种定位方法还是不行,昨天就这样带着疑惑过去了。今天上班后又开始思考这个问题,一步一步实践,最终通过selenium IDE的脚本发现是因为忘记了切换frame,在代码中补充了一段代码Login.dr.switchTo().frame("banner");问题果然解决了。
一、Login类用来放置登录的公用方法,代码如下:
public class Login {
public static WebDriver dr;
//登录方法
public static void main(String uname,String pword){
//打开firefox并最大化
System.setProperty("webdriver.firefox.bin",
"D:\\Program Files\\Mozilla Firefox\\firefox.exe");
dr = new FirefoxDriver();
dr.manage().window().maximize();
dr.get(Context_variables.url);
//获取用户名和密码框元素
WebElement uname1=dr.findElement(By.id("user_code"));
WebElement pword1=dr.findElement(By.id("user_pwd"));
//为用户名密码赋值
uname1.sendKeys(uname);
pword1.sendKeys(pword);
//点击确定按钮登录
WebElement btnclick=dr.findElement(By.xpath("/html/body/form/div/table/tbody/tr[4]/td[3]/img"));
btnclick.click();
}
}
二、LoginAll类点击登录完成后首页加载和欢迎语的验证,调用了Login登录方法
如果你没有用testng插件的话代码中的@Test可以去掉,不影响代码的运行结果
public class LoginAll {
@Test
public void LoginRight() {
Login.main(Context_variables.username, Context_variables.password);
try {
Thread.sleep(6000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// 切换到登录成功后新的窗口
Login.dr.switchTo().frame("banner");
// 等待欢迎语显示元素加载
(new WebDriverWait(Login.dr, 5))
.until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) {
return d.findElement(By.className("prompt"))
.isDisplayed();
}
});
// 获取欢迎语的值并提示判断正确性
WebElement title = Login.dr.findElement(By.className("prompt"))
.findElement(By.id("spInfo"));
Assert.assertEquals(Context_variables.helloword, title.getText());
}
}
三、Context_variables类用来存放URL、username和password等常量
public class Context_variables {
// 访问商户管理平台url
public static String url = "URL地址";
// 登录用户名、密码
public static String username = "用户名";
public static String password = "密码";
//登录成功欢迎语
public static String helloword = "登录成功页面欢迎语 ";
}