selenium调用电脑本地安装谷歌浏览器主要是通过谷歌浏览器支持debugging调试模式,支持的。这样做有两个好处:
1.绕过一些网站对selenium的检测
2.本地安装的谷歌浏览器记录一些用户名,密码,和其他的东西相比浏览器驱动每次打开相当于一个新的浏览器跟方便
下面直接看代码把:
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import cn.hutool.core.util.RuntimeUtil;
/**
* @author kk
* @Description 获取本地调试模式浏览器驱动
*/
public class GetLocalDebugModeWebDriver {
public static void main(String[] args) {
ChromeDriver driver = null;
// 调用cmd命令行,启动本地安装的谷歌浏览器
String command = "cmd /c start chrome --remote-debugging-port=9222";
// RuntimeUtil依赖hutool工具类
RuntimeUtil.execForStr(command);
// 加载驱动
System.setProperty("webdriver.chrome.driver", "浏览驱动路径");
ChromeOptions option = new ChromeOptions();
option.setExperimentalOption("debuggerAddress", "127.0.0.1:9222");
driver = new ChromeDriver(option);
driver.get("https://www.baidu.com/");
}
}
代码已经同步到码云上了地址是:https://gitee.com/yankangkk/watchmen/blob/master/src/main/java/com/watchmen/selenium/GetLocalDebugModeWebDriver.java