前言

        Selenium是一个用于Web应用程序测试的工具。Selenium测试直接运行在浏览器中,就像真正的用户在操作一样。支持的浏览器包括IE(7, 8, 9, 10, 11),Mozilla Firefox,Safari,Google Chrome,Opera,Edge等。这个工具的主要功能包括:测试与浏览器的兼容性——测试应用程序看是否能够很好得工作在不同浏览器和操作系统之上。测试系统功能——创建回归测试检验软件功能和用户需求。支持自动录制动作和自动生成.Net、Java、Perl等不同语言的测试脚本。

        我们一般用selenium爬取网页数据,下面介绍java使用selenium爬取网页所需要安装的环境。以chrome为例。


Windows环境

1、安装chrome浏览器

  • 首先确保电脑上安装了谷歌浏览器;
  • 然后确定谷歌浏览器版本,打开浏览器,点击帮助、关于Google Chrome

  •  查看浏览器版本

 2、下载ChromeDriver.exe

下载地址:https://registry.npmmirror/binary.html?path=chromedriver/

根据浏览器版本下载对应版本的ChromeDriver.exe,否则程序运行会报错。

3、将下载的ChromeDriver.exe放到浏览器安装路径

将ChromeDriver.exe放到浏览器安装路径,方便查找。


 Liunx环境 

以centos7为例。

1、安装chrome浏览器

  • 指定yum 源
wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun/repo/Centos-7.repo
  • 安装
curl https://intoli/install-google-chrome.sh | bash

ldd /opt/google/chrome/chrome | grep "not found"
  • 安装后,执行:当前目录生成一个图片。
google-chrome-stable --no-sandbox --headless --disable-gpu --screenshot https://www.baidu/

生成图片:

2、安装chromedriver

  • 查看chrome版本
google-chrome-stable --version

  •  根据chrome版本去上面的chromedriver下载地址找到对应的版本并下载

  •  下载完成后放到linux中,自己指定地址,由于是.zip格式,所以需要unzip解压,解压完成后即可。

Java整合使用

1、maven依赖

<dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-java</artifactId>
    <version>3.141.59</version>
</dependency>

或者自己下载jar包:

selenium下载地址:https://selenium.dev/downloads/ 

界面如下,选择java后点击下载。

 2、测试运行

public class TestController {

    public static void main(String[] args){
        System.getProperties().setProperty("webdriver.chrome.driver", "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe");
        ChromeOptions chromeOptions = new ChromeOptions();
        ChromeDriver chromeDriver = new ChromeDriver(chromeOptions);
        chromeDriver.get("https://www.baidu/");
    }
}

至此,整合成功。

更多推荐

Selenium入门(一)Java 搭建 Selenium 环境