前置条件:
mac 10.13.6
chrome浏览器 版本 68.0.3440.84(正式版本) (64 位)
chromedriver驱动
一.chrome浏览器下载
https://www.google.cn/chrome/
二.chromedriver驱动下载
各个版本:http://chromedriver.storage.googleapis.com/index.html
注:chromedriver需要和浏览器版本兼容,否则无法顺利解析
我下载的是2.41版本
http://chromedriver.storage.googleapis.com/2.41/chromedriver_mac64.zip
三.安装驱动
解压驱动到目录 /usr/local/bin/chromedriver
四.java代码
package test.selenium;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
public class ChromeMain {
public static void main(String[] args) throws IOException, InterruptedException {
long time = System.currentTimeMillis();
// 可省略,若驱动放在其他目录需指定驱动路径
//System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--headless");
ChromeDriver driver = new ChromeDriver(chromeOptions);
driver.get("http://baidu.com");
// 休眠1s,为了让js执行完
Thread.sleep(1000l);
// 网页源码
String source = driver.getPageSource();
System.out.println(source);
driver.close();
System.out.println("耗时:"+(System.currentTimeMillis()-time));
}
}
maven依赖
我这里使用的版本是2.53.1
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-remote-driver</artifactId>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-api</artifactId>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-chrome-driver</artifactId>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-support</artifactId>
</dependency>