package com.gubai.selenium;
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.interactions.Actions;
public class Login {
public WebDriver driver;
public void InitDriver() {
String url = "http://www.imooc.com/";
System.setProperty("webdriver.chrome.driver", "C:\\driver\\chromedriver.exe");
driver = new ChromeDriver();
driver.get(url);
driver.manage().window().maximize();
driver.findElement(By.id("js-signin-btn")).click();
}
public void loginscript() throws Exception {
this.InitDriver();
String username = "账号";
String emailElement = "email";
String userBy = "name";
String userpass = "密码";
String passBy = "name";
String passwordElement = "password";
String buttonElement = "btn-red";
String buttonBy = "className";
String headerElement = "header-avator";
String nameElement = "name";
Thread.sleep(3000);
WebElement user = driver.findElement(this.byStr(userBy, emailElement));
//driver.findElement(this.byStr(userBy, emailElement));
user.isDisplayed();
WebElement password = driver.findElement(this.byStr(passBy,passwordElement));
password.isDisplayed();
WebElement loginButton = driver.findElement(this.byStr(buttonBy,buttonElement));
loginButton.isDisplayed();
user.sendKeys(username);
password.sendKeys(userpass);
loginButton.click();
Thread.sleep(3000);
WebElement header = driver.findElement(By.id(headerElement));
header.isDisplayed();
Actions actions = new Actions(driver);
actions.moveToElement(header).perform();;
String userInfo = driver.findElement(By.className(nameElement)).getText();
System.out.println(userInfo);
if(userInfo.equals("mushishi_xu1")) {
System.out.print("登陆成功");
}else {
System.out.print("登录失败");
}
}
/**封装By by **/
public By byStr(String by, String local){
if(by.equals("id")) {
return By.id(local);
}else if(by.equals("name")){
return By.name(local);
}else if(by.equals("className")){
return By.className(local);
}else if(by.equals("xpath")){
return By.className(local);
}else{
return By.xpath(local);
}
}
public static void main(String[] args) throws Exception{
Login login = new Login();
login.loginscript();
}
}
转载于:https://www.cnblogs.com/igubai/p/7426150.html