public class Login { private WebDriver webDriver; private String baseUrl; private Logger logger = LoggerFactory.getLogger(this.getClass()); private WebElement element; public void openBrowser() throws Exception{ webDriver = new FirefoxDriver(); webDriver.get(baseUrl); } public void clickLoginLink(){ try { baseUrl = "http://www.lovo.cn/"; this.openBrowser(); element = webDriver.findElement(By.linkText("登录")); if(element != null){ element.click(); if(webDriver.findElement(By.id("logusername")) != null){ logger.info("正常跳转到登陆页"); }else{ logger.error("打开登陆页面失败"); } }else{ logger.error("没有找到登陆链接!!!"); } } catch (Exception e) { e.printStackTrace(); logger.error("发生未知错误!"); } } public void login(){ this.webDriver.findElement(By.id("logusername")).clear(); this.webDriver.findElement(By.id("logusername")).sendKeys("138****035"); this.webDriver.findElement(By.id("logpassword")).clear(); this.webDriver.findElement(By.id("logpassword")).sendKeys("123456"); this.webDriver.findElement(By.id("logimageCheck")).clear(); this.webDriver.findElement(By.id("logimageCheck")).sendKeys("5rkz"); this.webDriver.findElement(By.cssSelector("span.btntext")).click(); this.webDriver.findElement(By.cssSelector("div.text")).click(); if(this.webDriver.findElement(By.cssSelector("BODY")).getText().matches("^[\\s\\S]* 刘建东[\\s\\S]*$")){ this.logger.info("登陆成功!"); }else{ this.logger.error("登陆失败!"); } } public static void main(String[] args){ Login login = new Login(); login.clickLoginLink(); login.login(); } } |
有时候打开firefox的时候会报错,说没有安装firefox之类的错误,这是因为你改变了firefox的默认安装路径。这种情况下,你可以根据FirefoxBinary类实现。
方法如下:
public WebDriver openFirefox() throws Exception{ File file = new File("你的firefox的安装路径+firefox.exe"); //这里注意对\进行转义 FirefoxBinary firefoxBin = new FirefoxBinary(file); WebDriver webDriver = new FirefoxDriver(firefoxBin,null); return webDriver; } |
或者使用setCapabilit来设置
方法如下:
public WebDriver openFirefox() throws Exception{ DesiredCapabilities des = DesiredCapabilities.firefox(); des.setCapability("firefox_binary", "你的firefox的安装路径+firefox.exe"); WebDirver webDriver = new FirefoxDriver(des); return webDriver; } |
总结;
FirefoxDriver类有7个构造方法,意味着可以用7中方法打开firefox浏览器(其实比7种多),
FirefoxDriver() FirefoxDriver(Capabilities desiredCapabilities) FirefoxDriver(Capabilities desiredCapabilities, Capabilities requiredCapabilities) FirefoxDriver(FirefoxBinary binary, FirefoxProfile profile) FirefoxDriver(FirefoxBinary binary, FirefoxProfile profile, Capabilities capabilities) FirefoxDriver(FirefoxBinary binary, FirefoxProfile profile, Capabilities desiredCapabilities, Capabilities requiredCapabilities) FirefoxDriver(FirefoxProfile profile) |