Skip to content

一、Selenium介绍

1、简介

Selenium 有很多功能, 但其核心是 web 浏览器自动化的一个工具集, 它使用最好的技术来远程控制浏览器实例, 并模拟用户与浏览器的交互。

​ 它允许用户模拟终端用户执行的常见活动;将文本输入到字段中,选择下拉值和复选框,并单击文档中的链接。 它还提供许多其他控件,比如鼠标移动、任意 JavaScript 执行等等。

​ 虽然 Selenium 主要用于网站的前端测试,但其核心是浏览器用户代理库。 这些接口在应用程序中无处不在,它们鼓励与其他库进行组合,以满足您的目的。

官网https://www.selenium.dev/zh-cn/

文档https://www.selenium.dev/zh-cn/documentation/

2、WebDriver

WebDriver 以本地化方式驱动浏览器,就像用户在本地或使用 Selenium 服务器的远程机器上所做的那样,这标志着浏览器自动化的飞跃。

Selenium WebDriver 指的是语言绑定和各个浏览器控制代码的实现。 这通常被称为 WebDriver

  • WebDriver 被设计成一个简单和简洁的编程接口。
  • WebDriver 是一个简洁的面向对象 API。
  • 它能有效地驱动浏览器。

3、安装Selenium

1、安装Selenium类库

可以使用 Maven 安装 Java 的 Selenium 库。

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

selenium-java 依赖项支持在所有 Selenium 支持的浏览器中运行自动化项目。 如果只想在特定的浏览器中运行测试,可以在 pom.xml 文件中添加该浏览器的依赖项。 例如,您应该在 pom.xml 文件中添加以下依赖项,以便于只在 Firefox 中运行测试:

XML
<dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-firefox-driver</artifactId>
    <version>3.141.59</version>
</dependency>

同样,如果您只想在 Chrome 上运行测试,您应该添加以下依赖项:

XML
<dependency>
  <groupId>org.seleniumhq.selenium</groupId>
  <artifactId>selenium-chrome-driver</artifactId>
  <version>3.141.59</version>
</dependency>

也可以直接添加一下依赖,支持一些主流浏览器

https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-server/3.141.59

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

2、配置浏览器驱动

https://www.selenium.dev/zh-cn/documentation/webdriver/getting_started/install_drivers/