登录脚本重构Element
登录脚本重构Element
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(); this.elemnet(By.id("js-signin-btn")).click(); } public void loginscript() throws Exception { this.InitDriver(); String username = "18513199586"; String emailElement = "email"; String userBy = "name"; String userpass = "111111"; String passBy = "name"; String passwordElement = "password"; String buttonElement = "btn-red"; String buttonBy = "className"; String headerElement = "header-avator"; String nameElement = "name"; String headerBy = "id"; String nameinfo = "className"; Thread.sleep(3000); WebElement user = this.elemnet(this.byStr(userBy, emailElement)); //this.elemnet(this.byStr(userBy, emailElement)); user.isDisplayed(); WebElement password = this.elemnet(this.byStr(passBy,passwordElement)); password.isDisplayed(); WebElement loginButton = this.elemnet(this.byStr(buttonBy,buttonElement)); loginButton.isDisplayed(); user.sendKeys(username); password.sendKeys(userpass); loginButton.click(); Thread.sleep(3000); WebElement header = this.elemnet(this.byStr(headerBy, headerElement)); header.isDisplayed(); Actions actions = new Actions(driver); actions.moveToElement(header).perform();; String userInfo = this.elemnet(this.byStr(nameinfo, 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); } } /** * 封装Element * **/ public WebElement elemnet(By by) { WebElement ele = driver.findElement(by); return ele; } public static void main(String[] args) throws Exception{ Login login = new Login(); login.loginscript(); } }