selenium-java控制当前已经打开的 chrome浏览器窗口
一下方案的一个好处是一定程序避免反爬虫
1.首先来到安装 chrome浏览器 的文件夹下,例:C:\Program Files (x86)\Google\Chrome\Application
2.
在此界面打开 cmd窗口,
然后输入:chrome.exe —remote-debugging-port=9527 —user-data-dir=“D:\selenium\AutomationProfile” ,并回车。
这句代码的意思是启动 chrome浏览器 的调试模式,
- user-data-dirr=“F:\selenium\AutomationProfile” 是在单独的配置文件中启动 chrome浏览器,可以理解为 新的浏览器,记得创建对应文件夹哦;
- 其中 9527 为端口号,可自行指定
此时候,如果无误的话就可以看到桌面新打开了一个 chrome 浏览器了。
3.编写 Java程序获取控制 浏览器
3.1下载谷歌或者火狐等浏览器驱动chromedriver或者geckodriver并存放到某个文件夹下面,例如D:\\driver\\chromedriver.exe,不同的谷歌浏览器版本对应的谷歌驱动不同,参考https://blog.csdn.net/huilan_same/article/details/51896672
3.2使用System.setProperty(“webdriver.chrome.driver”,”D:\\driver\\chromedriver.exe”);设置谷歌浏览器驱动的位置
如果是火狐浏览器使用如下设置
System.setProperty(“webdriver.gecko.driver”,”D:\\driver\\geckodriver.exe”);
3.3引入jar包
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.4.0</version>
</dependency>
public static void main(String[] args) throws InterruptedException {
// 注意下载对应的驱动到文件夹下
// System.setProperty("webdriver.gecko.driver","D:\\driver\\geckodriver.exe");
System.setProperty("webdriver.chrome.driver","D:\\driver\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("debuggerAddress", "127.0.0.1:9527");
WebDriver driver = new ChromeDriver(options);
driver.get("http://www.baidu.com");
// 元素定位的8种方法 https://blog.csdn.net/qq_30990097/article/details/81386750
// WebElement loginLink = driver.findElement(By.xpath("//*[@id=\"clockLink\"]/button"));
// loginLink.click();
// System.out.println(loginLink.getText());
String title = driver.getTitle();
System.out.printf(title);
Thread.sleep(3000L);
driver.close();
}
还没有评论,来说两句吧...