admin管理员组

文章数量:1613955

前言

  • 环境参考 selenium:我的第一个程序
  • 使用已打开的chrome浏览器有啥好处
    • 不用验证登陆状态,可以先登陆,再爬虫
    • 不用反复开浏览器

开启命令行启动 chrome.exe

  1. 找到 chrome 安装目录。一般为 C:\Program Files (x86)\Google\Chrome\Application
  2. 打开 windows cmd 进入chrome安装目录。
cd C:\Program Files (x86)\Google\Chrome\Application
  1. 启动 chrome 程序,同时开启 remote-debugging-port 参数。
chrome.exe --remote-debugging-port=9222 --user-data-dir="C:\selenum\chrome_userdata"

编写程序

创建项目

在 Eclipse 中创建名为 02-UseOpenedChrome 的Maven项目。
添加依赖。
可以参考 selenium:我的第一个程序。

贴一下POM:

<project xmlns="http://maven.apache/POM/4.0.0"
	xmlns:xsi="http://www.w3/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache/POM/4.0.0 http://maven.apache/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>net.sayyy.sample.selenium</groupId>
	<artifactId>02-UseOpenedChrome</artifactId>
	<version>1.0</version>

	<properties>
		<java.version>1.8</java.version>
		<charset>UTF-8</charset>
		<!-- javac -source -->
		<mavenpiler.source>${java.version}</mavenpiler.source>
		<!-- javac -target -->
		<mavenpiler.target>${java.version}</mavenpiler.target>
		<!-- 编译时的编码 -->
		<mavenpiler.encoding>${charset}</mavenpiler.encoding>
		<project.build.sourceEncoding>${charset}</project.build.sourceEncoding>
		<project.reporting.outputEncoding>${charset}</project.reporting.outputEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.seleniumhq.selenium</groupId>
			<artifactId>selenium-java</artifactId>
			<version>3.9.1</version>
		</dependency>
	</dependencies>
</project>

编写 StartWebDriver 类

package net.sayyy.sample.selenium;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

public class StartWebDriver {

	public static void main(String[] args) {
		System.setProperty("webdriver.chrome.driver", "C:\\selenum\\chromedriver_win32_80\\chromedriver.exe"); 
		
		ChromeOptions options = new ChromeOptions();
		options.setExperimentalOption("debuggerAddress", "127.0.0.1:9222"); //(1)
		
		WebDriver driver = new ChromeDriver(options);
		try {
			driver.get("https://taobao");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			driver.quit(); //(2)
		}
	}

}

(1) 设置debuggerAddress。
(2) 退出 driver 。因为chrome不是driver创建的,所以退出driver不会关闭chrome。

启动 StartWebDriver 类

启动后效果与 selenium:我的第一个程序 一样。

结尾

至此完成了程序。
代码参考: https://gitee/sayyy/sample-selenium-java/tree/master/02-UseOpenedChrome

本文标签: 浏览器seleniumchrome