Selenium+Java+Webdriver+Chrome登录操作 谷歌浏览器通过设置启动参数保存登陆状态

694 阅读1分钟

网上这块设置参数的java的太少了,通过不懈努力,终于实现了,记录一下:
需要注意的是如果有正在运行的浏览器正在运行,用户文件就读取不成功,所以必须在运行前将谷歌浏览器的窗口全部关闭

package com.test.action;

import java.util.concurrent.TimeUnit;

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.chrome.ChromeOptions;
import org.openqa.selenium.remote.server.Session;
import org.testng.annotations.Optional;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

import com.test.util.ChromeUtil;
import com.test.util.ParseProperties;


/**
 * 系統登录相关操作
 * @author Mickey
 *
 */
public class LoginAction {
	public WebDriver driver;
	public ChromeOptions options;
	private ParseProperties testData = new ParseProperties(
			"C:\\workspace\\testHxams\\testData.properties");
	ChromeUtil chromeUtil = new ChromeUtil();

	public void createLogin() throws Exception {				
		// 指定浏览器驱动路径(Selenium3新特性)
        System.setProperty ( "webdriver.chrome.driver", "C:\\Program Files\\Google\\Chrome\\Application\\chromedriver.exe" );
        
        // 创建一个ChromeDriver实例
        options = new ChromeOptions();
		options.addArguments("user-data-dir=C:\\Users\\Mickey\\AppData\\Local\\Google\\Chrome\\User Data");
		driver = new ChromeDriver(options);	
		// 设置隐式等待
		driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
		System.out.println("-----------url:"+testData.getData("url")+"----------");
		// 打开浏览器
		driver.get(testData.getData("url"));
		// 通过输入框的id查找到输入框
//		// 在搜索输入框中输入用户名
		System.out.println("----------username:"+testData.getData("uname")+"---------");
		driver.findElement(By.id("name")).sendKeys(testData.getData("uname"));
//		WebElement password = driver.findElement(By.cssSelector("input[type='password'][class='el-input__inner']"));
//		chromeUtil.highlight(password, driver);
//		password.sendKeys(pwd);
		driver.findElement(By.cssSelector("input[type='password'][class='el-input__inner']")).sendKeys(testData.getData("pwd"));
//		WebElement btn_login = driver.findElement(By.cssSelector(".login-btn>button:first-child"));
//		btn_login.click();
		driver.findElement(By.cssSelector(".login-btn>button:first-child")).click();
		System.out.println("----------登录成功----------");	
	}	
	
	public void shutDown() {
		// 关闭浏览器
		driver.quit();
	}
	
}