WebDriver 以本地化方式驱动浏览器,就像用户在本地或使用 Selenium 服务器的远程机器上所做的那样,这标志着浏览器自动化的飞跃。
Selenium WebDriver 指的是语言绑定和各个浏览器控制代码的实现。 这通常被称为 WebDriver。
Selenium WebDriver 是 W3C 推荐标准
WebDriver 被设计成一个简单和简洁的编程接口。
WebDriver 是一个简洁的面向对象 API。
它能有效地驱动浏览器。
WebDriver 以本地化方式驱动浏览器,就像用户在本地或使用 Selenium 服务器的远程机器上所做的那样,这标志着浏览器自动化的飞跃。
Selenium WebDriver 指的是语言绑定和各个浏览器控制代码的实现。 这通常被称为 WebDriver。
Selenium WebDriver 是 W3C 推荐标准
WebDriver 被设计成一个简单和简洁的编程接口。
WebDriver 是一个简洁的面向对象 API。
它能有效地驱动浏览器。
Selenium 通过使用 WebDriver 支持市场上所有主流浏览器的自动化。 Webdriver 是一个 API 和协议,它定义了一个语言中立的接口,用于控制 web 浏览器的行为。 每个浏览器都有一个特定的 WebDriver 实现,称为驱动程序。 驱动程序是负责委派给浏览器的组件,并处理与 Selenium 和浏览器之间的通信。
这种分离是有意识地努力让浏览器供应商为其浏览器的实现负责的一部分。 Selenium 在可能的情况下使用这些第三方驱动程序, 但是在这些驱动程序不存在的情况下,它也提供了由项目自己维护的驱动程序。
Selenium 框架通过一个面向用户的界面将所有这些部分连接在一起, 该界面允许透明地使用不同的浏览器后端, 从而实现跨浏览器和跨平台自动化。
Selenium 设置与其他商业工具的设置完全不同。 要在自动化项目中使用 Selenium,您需要为您选择的语言安装语言绑定库。 此外,对于要自动运行并运行测试的浏览器,您将需要 WebDriver 二进制文件。
安装Selenium可分为三个步骤:
如果您希望从低代码/录制和播放工具开始, 请检查 Selenium IDE
完成安装后,可以在你的文档 starting page 中运行. 然后前往 WebDriver 部分 了解更多关于 使用Selenium实现浏览器自动化的信息.
首先,您需要为自动化项目安装 Selenium 绑定库。 库的安装过程取决于您选择使用的语言。
查看该库所支持java的最低版本 here.
应熟练掌握build tool以安装支持java的Selenium库
具体的依赖位于项目中的 pom.xml
文件:
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.8.0</version>
</dependency>
具体的依赖位于项目中的 build.gradle
文件中的 testImplementation
:
testImplementation 'org.seleniumhq.selenium:selenium-java:4.8.0'
该库所支持的Python版本最低版本可以在
支持的Python版本
章节中找到 PyPi
这里提供了几种不同的方式来安装 Selenium .
pip install selenium
此外你可以从这里下载 PyPI source archive (selenium-x.x.x.tar.gz) 并通过: setup.py 文件安装:
python setup.py install
为了在项目中使用它,需要将它添加到 requirements.txt
文件中:
selenium==4.8.2
Selenium 所支持的所有平台的列表一览 见诸于 Nuget
该处阐述了一些安装Selenium的选项.
Install-Package Selenium.WebDriver
dotnet add package Selenium.WebDriver
在 csproj
文件里, 具体的依赖 PackageReference
(包参数) 位于 ItemGroup
(项目组)中:
<PackageReference Include="Selenium.WebDriver" Version="4.8.1" />
更多的注意事项,适用于使用 Visual Studio Code (vscode) 和 C#
安装兼容的 .NET SDK 作为章节的先决条件
同时安装 vscode 的扩展 (Ctrl-Shift-X)以适配 C# 和 NuGet
可以遵照此处进行 操作指南
创建 C# 控制台项目并运行 “Hello World”.
你也可以用命令行 dotnet new NUnit
创建NUnit初阶项目.
确保文件 %appdata%\NuGet\nuget.config
已经配置完成,就像某位开发者报告的问题一样,它可能因为某种因素被自动清空.
如果 nuget.config
是空的,或者未配置的,那么 .NET 创建的Selenium项目可能失败.
加入如下章节到文件 nuget.config
如果出现清空的情况:
<configuration>
<packageSources>
<add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
<add key="nuget.org" value="https://www.nuget.org/api/v2/" />
</packageSources>
...
更多关于 nuget.config
的信息 点击.
你可能需要按照自己的需求配置 nuget.config
.
现在,返回 vscode ,按下 Ctrl-Shift-P, 然后键入 “NuGet Add Package”, 并选择自己需要的 Selenium 包,例如 Selenium.WebDriver
.
按下回车并选择版本.
现在你可以使用说明文档中关于 C# vscode下的案例了.
你可以查看 Selenium 对 Ruby 版本支持和最低支持. 具体位于 rubygems.org
Selenium 可以使用两种不同方法安装.
gem install selenium-webdriver
gem 'selenium-webdriver', '= 4.8.6'
You can find the minimum required version of Node for any given version of Selenium in the
你可以在此查看 Selenium 对 Node 的版本支持情况
位于 Node Support Policy
中的相关章节 npmjs
Selenium is typically installed using npm.
npm install selenium-webdriver
在你的项目 package.json
, 必须加入到 dependencies
:
"selenium-webdriver": "^4.8.1"
通过WebDriver, Selenium支持市场上所有主要浏览器, 如Chrome、Firefox、Internet Explorer、Edge和Safari. WebDriver尽量使用浏览器内置的自动化支持 来驱动浏览器.
由于除Internet Explorer之外的所有驱动程序实现 都是由浏览器供应商自己提供的, 因此标准Selenium发行版中不包括这些驱动程序. 本节介绍了使用不同浏览器的基本要求.
在我们的驱动程序配置 文档中 阅读有关启动驱动程序的更多高级选项.
Page being translated from English to Chinese. Do you speak Chinese? Help us to translate it by sending us pull requests!
Selenium Manager可以帮助你获得一个运行Selenium的开箱即用的环境。
如果在PATH
中没有找到Chrome、Firefox和Edge的驱动,Selenium Manager的Beta 1版将为它们配置。
不需要额外的配置。如果有必要,Selenium Manager的未来版本也会在必要时一同下载浏览器。
在这篇公告中了解更多有关 Selenium Manager 的信息。
大多数机器会自动更新浏览器, 但不会自动更新驱动程序. 为了确保为浏览器提供正确的驱动程序, 这里有许多第三方库可为您提供帮助.
注意: 这个软件包目前不能用于IEDriverServer v4以上的版本。
import io.github.bonigarcia.wdm.WebDriverManager;
setup()
: WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();
from webdriver_manager.chrome import ChromeDriverManager
install()
获取管理器使用的位置, 并将其传递到服务类中 service = ChromeService(executable_path=ChromeDriverManager().install())
driver = webdriver.Chrome(service=service)
using WebDriverManager;
using WebDriverManager.DriverConfigs.Impl;
SetUpDriver()
时需要一个配置类: new DriverManager().SetUpDriver(new ChromeConfig());
var driver = new ChromeDriver();
gem 'webdrivers', '~> 5.0'
require 'webdrivers'
driver = Selenium::WebDriver.for :chrome
暂时还没有推荐的JavaScript驱动管理器
import io.github.bonigarcia.wdm.WebDriverManager;
WebDriverManager.chromedriver().setup()
val driver: WebDriver = ChromeDriver()
PATH
环境变量此选项首先需要手动下载驱动程序 (有关链接, 请参阅快速参考 部分).
这是一个灵活的选项, 可以在不更新代码的情况下更改驱动程序的位置, 并且可以在多台机器上工作, 而不需要每台机器将驱动程序放在同一位置.
您可以将驱动程序放置在路径中已列出的目录中,
也可以将其放置在目录中并将其添加到PATH
.
PATH
上已有哪些目录,
请打开命令提示符/终端并键入:要查看PATH
上已经有哪些目录, 请打开Terminal并执行
echo $PATH
如果驱动程序的位置不在列出的目录中, 可以将新目录添加到PATH:
echo 'export PATH=$PATH:/path/to/driver' >> ~/.bash_profile
source ~/.bash_profile
您可以通过启动驱动程序来测试其是否被正确添加:
chromedriver
要查看PATH
上已经有哪些目录, 请打开Terminal并执行:
echo $PATH
如果驱动程序的位置不在列出的目录中, 可以将新目录添加到PATH:
echo 'export PATH=$PATH:/path/to/driver' >> ~/.zshenv
source ~/.zshenv
您可以通过启动驱动程序来测试其是否被正确添加:
chromedriver
要查看PATH
上已经有哪些目录, 请打开命令提示符并执行:
echo %PATH%
如果驱动程序的位置不在列出的目录中, 可以将新目录添加到PATH:
setx PATH "%PATH%;C:\WebDriver\bin"
您可以通过启动驱动程序来测试其是否被正确添加:
chromedriver.exe
如果PATH
配置正确,
您将看到一些与驱动程序启动相关的输出:
Starting ChromeDriver 95.0.4638.54 (d31a821ec901f68d0d34ccdbaea45b4c86ce543e-refs/branch-heads/4638@{#871}) on port 9515
Only local connections are allowed.
Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.
ChromeDriver was started successfully.
想要重新控制命令提示符可以按下 Ctrl+C
与上面的选项3类似, 您需要手动下载驱动程序(有关链接, 请参阅快速参考 部分). 在代码中指定位置本身的优点是 不需要指出系统上的环境变量, 但缺点是使代码的灵活性大大降低.
System.setProperty("webdriver.chrome.driver","/path/to/chromedriver");
ChromeDriver driver = new ChromeDriver();
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
service = Service(executable_path="/path/to/chromedriver")
driver = webdriver.Chrome(service=service)
var driver = new ChromeDriver(@"C:\WebDriver\bin");
service = Selenium::WebDriver::Service.chrome(path: '/path/to/chromedriver')
driver = Selenium::WebDriver.for :chrome, service: service
const {Builder} = require('selenium-webdriver');
const chrome = require('selenium-webdriver/chrome');
const service = new chrome.ServiceBuilder('/path/to/chromedriver');
const driver = new Builder().forBrowser('chrome').setChromeService(service).build();
import org.openqa.selenium.chrome.ChromeDriver
fun main(args: Array<String>) {
System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver")
val driver = ChromeDriver()
}
浏览器 | 支持的操作系统 | 维护者 | 下载 | 问题追溯 |
---|---|---|---|---|
Chromium/Chrome | Windows/macOS/Linux | 下载 | Issues | |
Firefox | Windows/macOS/Linux | Mozilla | 下载 | Issues |
Edge | Windows/macOS/Linux | Microsoft | 下载 | Issues |
Internet Explorer | Windows | Selenium Project | 下载 | Issues |
Safari | macOS High Sierra and newer | Apple | 内置 | Issues |
备注:Opera驱动不再适用于Selenium的最新功能,目前官方不支持。
当你完成 Selenium安装 and 驱动安装 后, 便可以开始书写Selenium脚本了.
Selenium所做的一切, 就是发送给浏览器命令, 用以执行某些操作或为信息发送请求. 您将使用Selenium执行的大部分操作, 都是以下基本命令的组合:
关于如何启动会话,请浏览我们的文档 驱动会话
WebDriver driver = new ChromeDriver();
driver = webdriver.Chrome()
IWebDriver driver = new ChromeDriver();
driver = Selenium::WebDriver.for :chrome
driver = await new Builder().forBrowser('chrome').build();
driver = ChromeDriver()
在本例中, 我们 导航 到一个网页.
driver.get("https://www.selenium.dev/selenium/web/web-form.html");
driver.get("https://www.selenium.dev/selenium/web/web-form.html")
driver.Navigate().GoToUrl("https://www.selenium.dev/selenium/web/web-form.html");
driver.get('https://www.selenium.dev/selenium/web/web-form.html')
await driver.get('https://www.selenium.dev/selenium/web/web-form.html');
driver.get("https://www.selenium.dev/selenium/web/web-form.html")
您可以请求一系列关于浏览器的信息 , 包括窗口句柄、浏览器尺寸/位置、cookie、警报等.
String title = driver.getTitle();
title = driver.title
var title = driver.Title;
title = driver.title
let title = await driver.getTitle();
val title = driver.title
将代码与浏览器的当前状态同步 是Selenium面临的最大挑战之一, 做好它是一个高级主题.
基本上, 您希望在尝试定位元素之前, 确保该元素位于页面上, 并且在尝试与该元素交互之前, 该元素处于可交互状态.
隐式等待很少是最好的解决方案, 但在这里最容易演示, 所以我们将使用它作为占位符.
阅读更多关于等待策略 的信息.
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));
driver.implicitly_wait(0.5)
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(500);
driver.manage.timeouts.implicit_wait = 500
await driver.manage().setTimeouts({implicit: 500});
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500))
大多数Selenium会话中的主要命令都与元素相关, 如果不先找到元素, 就无法与之交互.
WebElement textBox = driver.findElement(By.name("my-text"));
WebElement submitButton = driver.findElement(By.cssSelector("button"));
text_box = driver.find_element(by=By.NAME, value="my-text")
submit_button = driver.find_element(by=By.CSS_SELECTOR, value="button")
var textBox = driver.FindElement(By.Name("my-text"));
var submitButton = driver.FindElement(By.TagName("button"));
text_box = driver.find_element(name: 'my-text')
submit_button = driver.find_element(tag_name: 'button')
let textBox = await driver.findElement(By.name('my-text'));
let submitButton = await driver.findElement(By.css('button'));
var textBox = driver.findElement(By.name("my-text"))
val submitButton = driver.findElement(By.cssSelector("button"))
对于一个元素, 只有少数几个操作可以执行, 但您将经常使用它们.
textBox.sendKeys("Selenium");
submitButton.click();
text_box.send_keys("Selenium")
submit_button.click()
textBox.SendKeys("Selenium");
submitButton.Click();
text_box.send_keys('Selenium')
submit_button.click
await textBox.sendKeys('Selenium');
await submitButton.click();
textBox.sendKeys("Selenium")
submitButton.click()
元素存储了很多被请求的信息.
String value = message.getText();
value = message.text
var value = message.Text;
value = message.text
let value = await message.getText();
val value = message.getText()
这将结束驱动程序进程, 默认情况下, 该进程也会关闭浏览器. 无法向此驱动程序实例发送更多命令.
driver.quit();
driver.quit()
driver.Quit();
driver.quit
after(async () => await driver.quit());
driver.quit()
让我们将这8个部分组合成一个完整的脚本, 包括需要使用的库:
按照选项卡底部的链接查看代码示例, 因为它将使用测试运行程序而不是独立文件执行.
package dev.selenium.getting_started;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.time.Duration;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class FirstScriptTest {
@Test
public void eightComponents() {
WebDriver driver = new ChromeDriver();
driver.get("https://www.selenium.dev/selenium/web/web-form.html");
String title = driver.getTitle();
assertEquals("Web form", title);
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));
WebElement textBox = driver.findElement(By.name("my-text"));
WebElement submitButton = driver.findElement(By.cssSelector("button"));
textBox.sendKeys("Selenium");
submitButton.click();
WebElement message = driver.findElement(By.id("message"));
String value = message.getText();
assertEquals("Received!", value);
driver.quit();
}
}
from selenium import webdriver
from selenium.webdriver.common.by import By
def test_eight_components():
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/web-form.html")
title = driver.title
assert title == "Web form"
driver.implicitly_wait(0.5)
text_box = driver.find_element(by=By.NAME, value="my-text")
submit_button = driver.find_element(by=By.CSS_SELECTOR, value="button")
text_box.send_keys("Selenium")
submit_button.click()
message = driver.find_element(by=By.ID, value="message")
value = message.text
assert value == "Received!"
driver.quit()
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
namespace SeleniumDocs.GettingStarted
{
[TestClass]
public class FirstScriptTest
{
[TestMethod]
public void ChromeSession()
{
IWebDriver driver = new ChromeDriver();
driver.Navigate().GoToUrl("https://www.selenium.dev/selenium/web/web-form.html");
var title = driver.Title;
Assert.AreEqual("Web form", title);
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(500);
var textBox = driver.FindElement(By.Name("my-text"));
var submitButton = driver.FindElement(By.TagName("button"));
textBox.SendKeys("Selenium");
submitButton.Click();
var message = driver.FindElement(By.Id("message"));
var value = message.Text;
Assert.AreEqual("Received!", value);
driver.Quit();
}
}
}
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'First Script' do
it 'uses eight components' do
driver = Selenium::WebDriver.for :chrome
driver.get('https://www.selenium.dev/selenium/web/web-form.html')
title = driver.title
expect(title).to eq('Web form')
driver.manage.timeouts.implicit_wait = 500
text_box = driver.find_element(name: 'my-text')
submit_button = driver.find_element(tag_name: 'button')
text_box.send_keys('Selenium')
submit_button.click
message = driver.find_element(id: 'message')
value = message.text
expect(value).to eq('Received!')
driver.quit
end
end
const {By, Builder, Browser} = require('selenium-webdriver');
const {suite} = require('selenium-webdriver/testing');
const assert = require("assert");
suite(function (env) {
describe('First script', function () {
let driver;
before(async function () {
driver = await new Builder().forBrowser('chrome').build();
});
after(async () => await driver.quit());
it('First Selenium script', async function () {
await driver.get('https://www.selenium.dev/selenium/web/web-form.html');
let title = await driver.getTitle();
assert.equal("Web form", title);
await driver.manage().setTimeouts({implicit: 500});
let textBox = await driver.findElement(By.name('my-text'));
let submitButton = await driver.findElement(By.css('button'));
await textBox.sendKeys('Selenium');
await submitButton.click();
let message = await driver.findElement(By.id('message'));
let value = await message.getText();
assert.equal("Received!", value);
});
});
}, { browsers: [Browser.CHROME, Browser.FIREFOX]});
package dev.selenium.getting_started
import io.github.bonigarcia.wdm.WebDriverManager
import org.junit.jupiter.api.*
import org.junit.jupiter.api.Assertions.assertEquals
import org.openqa.selenium.By
import org.openqa.selenium.WebDriver
import org.openqa.selenium.chrome.ChromeDriver
import java.time.Duration
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class FirstScriptTest {
private lateinit var driver: WebDriver
@BeforeAll
fun setupAll() {
WebDriverManager.chromedriver().setup()
}
@BeforeEach
fun setup() {
driver = ChromeDriver()
}
@AfterEach
fun teardown() {
driver.quit()
}
@Test
fun eightComponents() {
driver.get("https://www.selenium.dev/selenium/web/web-form.html")
val title = driver.title
assertEquals("Web form", title)
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500))
var textBox = driver.findElement(By.name("my-text"))
val submitButton = driver.findElement(By.cssSelector("button"))
textBox.sendKeys("Selenium")
submitButton.click()
val message = driver.findElement(By.id("message"))
val value = message.getText()
assertEquals("Received!", value)
}
}
If you are using Selenium for testing, you will want to execute your Selenium code using test runner tools.
Many of the code examples in this documentation can be found in our example repositories. There are multiple options in each language, but here is what we are using in our examples:
Install Mocha Test runner using below command in your terminal
npm install mocha
and run your tests using below command
mocha firstScript.spec.js
利用你所学的知识, 构建你的Selenium代码.
当您发现需要更多功能时, 请阅读我们的WebDriver文档的其余部分.
如果您使用的是官方支持的语言 (Ruby、JavaScript、C#、Python和Java), 那么升级到Selenium 4应该是一个轻松的过程. 在某些情况下可能会出现一些问题, 本指南将帮助您解决这些问题. 我们将完成升级项目依赖项的步骤, 并了解版本升级带来的主要反对意见和更改.
请按照以下步骤升级到Selenium 4:
注意:在开发Selenium 3.x版本的同时, 实现了对W3C WebDriver标准的支持. 此新协议和遗留JSON Wire协议均受支持. 在3.11版前后, Selenium代码与W3C 1级规范兼容. 最新版本的Selenium 3中的W3C兼容代码将在Selenium 4中正常工作.
Selenium 4 移除了对遗留协议的支持,
并在底层实现上默认使用 W3C WebDriver 标准.
对于大多数情况, 这种实现不会影响终端用户.
主要的例外是 Capabilities
和 Actions
类.
如果测试capabilities的结构不符合 W3C标准,
可能会导致会话无法正常开启.
以下是 W3C WebDriver 标准capabilities列表:
browserName
browserVersion
(替代 version
)platformName
(替代 platform
)acceptInsecureCerts
pageLoadStrategy
proxy
timeouts
unhandledPromptBehavior
可以在以下位置找到标准capabilities的最新列表 W3C WebDriver.
上面列表中未包含的任何capability,
都需要包含供应商前缀.
这适用于浏览器特定capability
以及云供应商特定capability.
例如, 如果您的云供应商为您的测试
使用 build
和 name
capability,
您需要将它们包装在一个 cloud: options
块中
(请与您的云供应商联系以获取适当的前缀).
DesiredCapabilities caps = DesiredCapabilities.firefox();
caps.setCapability("platform", "Windows 10");
caps.setCapability("version", "92");
caps.setCapability("build", myTestBuild);
caps.setCapability("name", myTestName);
WebDriver driver = new RemoteWebDriver(new URL(cloudUrl), caps);
caps = {};
caps['browserName'] = 'Firefox';
caps['platform'] = 'Windows 10';
caps['version'] = '92';
caps['build'] = myTestBuild;
caps['name'] = myTestName;
DesiredCapabilities caps = new DesiredCapabilities();
caps.SetCapability("browserName", "firefox");
caps.SetCapability("platform", "Windows 10");
caps.SetCapability("version", "92");
caps.SetCapability("build", myTestBuild);
caps.SetCapability("name", myTestName);
var driver = new RemoteWebDriver(new Uri(CloudURL), caps);
caps = Selenium: : WebDriver: : Remote: : Capabilities.firefox
caps[: platform] = 'Windows 10'
caps[: version] = '92'
caps[: build] = my_test_build
caps[: name] = my_test_name
driver = Selenium: : WebDriver.for : remote, url: cloud_url, desired_capabilities: caps
caps = {}
caps['browserName'] = 'firefox'
caps['platform'] = 'Windows 10'
caps['version'] = '92'
caps['build'] = my_test_build
caps['name'] = my_test_name
driver = webdriver.Remote(cloud_url, desired_capabilities=caps)
FirefoxOptions browserOptions = new FirefoxOptions();
browserOptions.setPlatformName("Windows 10");
browserOptions.setBrowserVersion("92");
Map<String, Object> cloudOptions = new HashMap<>();
cloudOptions.put("build", myTestBuild);
cloudOptions.put("name", myTestName);
browserOptions.setCapability("cloud: options", cloudOptions);
WebDriver driver = new RemoteWebDriver(new URL(cloudUrl), browserOptions);
capabilities = {
browserName: 'firefox',
browserVersion: '92',
platformName: 'Windows 10',
'cloud: options': {
build: myTestBuild,
name: myTestName,
}
}
var browserOptions = new FirefoxOptions();
browserOptions.PlatformName = "Windows 10";
browserOptions.BrowserVersion = "92";
var cloudOptions = new Dictionary<string, object>();
cloudOptions.Add("build", myTestBuild);
cloudOptions.Add("name", myTestName);
browserOptions.AddAdditionalOption("cloud: options", cloudOptions);
var driver = new RemoteWebDriver(new Uri(CloudURL), browserOptions);
options = Selenium: : WebDriver: : Options.firefox
options.browser_version = 'latest'
options.platform_name = 'Windows 10'
cloud_options = {}
cloud_options[: build] = my_test_build
cloud_options[: name] = my_test_name
options.add_option('cloud: options', cloud_options)
driver = Selenium: : WebDriver.for : remote, url: cloud_url, capabilities: options
from selenium.webdriver.firefox.options import Options as FirefoxOptions
options = FirefoxOptions()
options.browser_version = '92'
options.platform_name = 'Windows 10'
cloud_options = {}
cloud_options['build'] = my_test_build
cloud_options['name'] = my_test_name
options.set_capability('cloud: options', cloud_options)
driver = webdriver.Remote(cloud_url, options=options)
在 Java 绑定(FindsBy
接口)中
查找元素的工具方法已被删除
因为它们仅供内部使用.
以下代码示例更好地解释了这一点.
使用 findElement*
查找单个元素
driver.findElementByClassName("className");
driver.findElementByCssSelector(".className");
driver.findElementById("elementId");
driver.findElementByLinkText("linkText");
driver.findElementByName("elementName");
driver.findElementByPartialLinkText("partialText");
driver.findElementByTagName("elementTagName");
driver.findElementByXPath("xPath");
driver.findElement(By.className("className"));
driver.findElement(By.cssSelector(".className"));
driver.findElement(By.id("elementId"));
driver.findElement(By.linkText("linkText"));
driver.findElement(By.name("elementName"));
driver.findElement(By.partialLinkText("partialText"));
driver.findElement(By.tagName("elementTagName"));
driver.findElement(By.xpath("xPath"));
使用 findElements*
查找多个元素
driver.findElementsByClassName("className");
driver.findElementsByCssSelector(".className");
driver.findElementsById("elementId");
driver.findElementsByLinkText("linkText");
driver.findElementsByName("elementName");
driver.findElementsByPartialLinkText("partialText");
driver.findElementsByTagName("elementTagName");
driver.findElementsByXPath("xPath");
driver.findElements(By.className("className"));
driver.findElements(By.cssSelector(".className"));
driver.findElements(By.id("elementId"));
driver.findElements(By.linkText("linkText"));
driver.findElements(By.name("elementName"));
driver.findElements(By.partialLinkText("partialText"));
driver.findElements(By.tagName("elementTagName"));
driver.findElements(By.xpath("xPath"));
检查下面的小节以安装 Selenium 4 并升级您的项目依赖项.
升级 Selenium 的过程取决于所使用的构建工具.
我们将涵盖Java 中最常见的
Maven 和
Gradle .
所需的最低 Java 版本仍然是 8.
<dependencies>
<!-- more dependencies ... -->
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.141.59</version>
</dependency>
<!-- more dependencies ... -->
</dependencies>
<dependencies>
<!-- more dependencies ... -->
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.4.0</version>
</dependency>
<!-- more dependencies ... -->
</dependencies>
进行更改后,
您可以在pom.xml
文件的同一目录中
执行 mvn clean compile
.
plugins {
id 'java'
}
group 'org.example'
version '1.0-SNAPSHOT'
repositories {
mavenCentral()
}
dependencies {
testImplementation 'org.junit.jupiter: junit-jupiter-api: 5.7.0'
testRuntimeOnly 'org.junit.jupiter: junit-jupiter-engine: 5.7.0'
implementation group: 'org.seleniumhq.selenium', name: 'selenium-java', version: '3.141.59'
}
test {
useJUnitPlatform()
}
plugins {
id 'java'
}
group 'org.example'
version '1.0-SNAPSHOT'
repositories {
mavenCentral()
}
dependencies {
testImplementation 'org.junit.jupiter: junit-jupiter-api: 5.7.0'
testRuntimeOnly 'org.junit.jupiter: junit-jupiter-engine: 5.7.0'
implementation group: 'org.seleniumhq.selenium', name: 'selenium-java', version: '4.4.0'
}
test {
useJUnitPlatform()
}
进行更改后,
您可以在 build.gradle 文件所在的同一目录中
执行./gradlew clean build
.
要检查所有 Java 版本, 您可以前往 MVNRepository .
在 C# 中获取 Selenium 4 更新的
地方是 NuGet .
在下面包
Selenium.WebDriver
你可以获得更新到最新版本的说明.
在 Visual Studio 内部,
您可以通过 NuGet 包管理器执行:
PM> Install-Package Selenium.WebDriver -Version 4.4.0
使用 Python 的最重要变化是所需的最低版本.
Selenium 4 将至少需要 Python 3.7 或更高版本.
更多详细信息可以在
Python 包索引 .
基于命令行做升级的话, 你可以执行:
pip install selenium==4.4.3
Selenium 4 的更新细节
可以在RubyGems中的gem发现
selenium-webdriver .
要安装最新版本,
您可以执行:
gem install selenium-webdriver
将以下内容添加到你的Gemfile:
gem 'selenium-webdriver', '~> 4.4.0'
可以在 Node 包管理器中找到 selenium-webdriver 包,
npmjs .
Selenium 4 可以在
这里 找到.
要安装, 你可以执行:
npm install selenium-webdriver
或者, 更新你的 package.json
并运行 npm install
:
{
"name": "selenium-tests",
"version": "1.0.0",
"dependencies": {
"selenium-webdriver": "^4.4.0"
}
}
这是一组代码示例, 它们将有助于克服 您升级到 Selenium 4 后 可能会遇到的弃用消息.
Timeout 中接收到的参数
已经从期望 (long time, TimeUnit unit)
切换到期待 (Duration duration)
.
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().timeouts().setScriptTimeout(2, TimeUnit.MINUTES);
driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
driver.manage().timeouts().scriptTimeout(Duration.ofMinutes(2));
driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(10));
等待现在也期望不同的参数.
WebDriverWait
现在期待一个 Duration
而不是以秒和毫秒为单位的 long
超时.
FluentWait
的工具方法
withTimeout
和 pollingEvery
已经从期望 (long time, TimeUnit unit)
切换到
期待(Duration duration)
.
new WebDriverWait(driver, 3)
.until(ExpectedConditions.elementToBeClickable(By.cssSelector("#id")));
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(30, TimeUnit.SECONDS)
.pollingEvery(5, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);
new WebDriverWait(driver, Duration.ofSeconds(3))
.until(ExpectedConditions.elementToBeClickable(By.cssSelector("#id")));
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(Duration.ofSeconds(30))
.pollingEvery(Duration.ofSeconds(5))
.ignoring(NoSuchElementException.class);
曾经可以将一组不同的capabilities合并到另一组中,
并且改变调用对象.
现在, 需要分配合并操作的结果.
MutableCapabilities capabilities = new MutableCapabilities();
capabilities.setCapability("platformVersion", "Windows 10");
FirefoxOptions options = new FirefoxOptions();
options.setHeadless(true);
options.merge(capabilities);
作为结果, options
对象被修改
MutableCapabilities capabilities = new MutableCapabilities();
capabilities.setCapability("platformVersion", "Windows 10");
FirefoxOptions options = new FirefoxOptions();
options.setHeadless(true);
options = options.merge(capabilities);
merge
调用的结果需要分配给一个对象.
在 GeckoDriver 出现之前,
Selenium 项目有一个驱动程序实现来自动化
Firefox(版本 <48).
但是, 不再需要此实现,
因为在最新版本的 Firefox 中它不起作用.
为避免升级到 Selenium 4 时出现重大问题,
setLegacy
选项将显示为已弃用.
建议停止使用旧的实现
并且只依赖 GeckoDriver.
以下代码将显示在升级之后弃用的 setLegacy
行.
FirefoxOptions options = new FirefoxOptions();
options.setLegacy(true);
BrowserType
BrowserType
接口已经存在很长时间了,
但是其已变为弃用
且推荐使用新的 Browser
接口.
MutableCapabilities capabilities = new MutableCapabilities();
capabilities.setCapability("browserVersion", "92");
capabilities.setCapability("browserName", BrowserType.FIREFOX);
MutableCapabilities capabilities = new MutableCapabilities();
capabilities.setCapability("browserVersion", "92");
capabilities.setCapability("browserName", Browser.FIREFOX);
AddAdditionalCapability
已弃用推荐使用AddAdditionalOption
替代.
以下为一个示例:
var browserOptions = new ChromeOptions();
browserOptions.PlatformName = "Windows 10";
browserOptions.BrowserVersion = "latest";
var cloudOptions = new Dictionary<string, object>();
browserOptions.AddAdditionalCapability("cloud: options", cloudOptions, true);
var browserOptions = new ChromeOptions();
browserOptions.PlatformName = "Windows 10";
browserOptions.BrowserVersion = "latest";
var cloudOptions = new Dictionary<string, object>();
browserOptions.AddAdditionalOption("cloud: options", cloudOptions);
executable_path 已弃用, 请传递一个服务对象
在Selenium 4中,
您需要从服务对象设置驱动程序的 可执行路径
,
以防止出现弃用警告.
(或者不要设置路径, 而是确保所需的驱动程序位于系统路径上.)
from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option("useAutomationExtension", False)
driver = webdriver.Chrome(executable_path=CHROMEDRIVER_PATH, options=options)
from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
options = webdriver.ChromeOptions()
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option("useAutomationExtension", False)
service = ChromeService(executable_path=CHROMEDRIVER_PATH)
driver = webdriver.Chrome(service=service, options=options)
我们已经过了升级到 Selenium 4 时要考虑的主要变化.
涵盖为升级准备测试代码时要涵盖的不同方面,
包括关于如何避免
使用Selenium新版本时
可能出现的潜在问题的建议.
最后, 我们还介绍了一系列您可能会遇到的升级问题,
分享这些问题的潜在修复方案.
本文最初发布于 https://saucelabs.com/resources/articles/how-to-upgrade-to-selenium-4
启动和停止会话, 用于打开和关闭浏览器.
创建会话对应于W3C的命令 新建会话
会话是通过初始化新的驱动类对象自动创建的.
每种语言都允许使用来自这些类 (或等效类) 之一的参数创建会话:
启动本地驱动的首要唯一参数 包括在本地计算机上有关启动所需驱动服务的信息.
用于启动远程驱动的首要唯一参数包括有关在何处执行代码的信息. 请浏览 远程驱动章节中的详细信息
退出会话对应于W3C的命令 删除会话.
重要提示: quit
方法与 close
方法不同,
建议始终使用 quit
来结束会话
在 Selenium 3 中, capabilities是借助"Desired Capabilities"类定义于会话中的. 从 Selenium 4 开始, 您必须使用浏览器选项类. 对于远程驱动程序会话, 浏览器选项实例是必需的, 因为它确定将使用哪个浏览器.
这些选项在 Capabilities 的 w3c 规范中进行了描述.
每个浏览器都有 自定义选项 , 是规范定义之外的内容.
此功能用于设置既定会话的 browserName
.
如果未在远端安装指定的浏览器,
则会话创建将失败
此功能是可选的, 用于在远程端设置可用的浏览器版本. 例如, 如果在仅安装80版本的系统上询问75版本的Chrome, 则会话创建将失败
共有三种类型的页面加载策略.
页面加载策略可以在此链接查询 document.readyState , 如下表所述:
策略 | 就绪状态 | 备注 |
---|---|---|
normal | complete | 默认值, 等待所有资源下载 |
eager | interactive | DOM 访问已准备就绪, 但诸如图像的其他资源可能仍在加载 |
none | Any | 完全不会阻塞 WebDriver |
文档的 document.readyState
属性描述当前文档的加载状态.
当通过URL导航到新页面时, 默认情况下, WebDriver将暂缓完成导航方法 (例如, driver.navigate().get())直到文档就绪状态完成. 这 并非意味着该页面已完成加载, 特别是对于使用 JavaScript 在就绪状态返回完成后 动态加载内容单页应用程序的站点. 另请注意此行为不适用于单击元素或提交表单后出现的导航行为.
如果由于下载对自动化不重要的资源(例如, 图像、css、js)
而需要很长时间才能加载页面,
您可以将默认参数normal
更改为
eager
或 none
以加快会话加载速度.
此值适用于整个会话,
因此请确保您的 等待策略
足够普适.
WebDriver一直等到 load 事件触发并返回.
import org.openqa.selenium.PageLoadStrategy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.chrome.ChromeDriver;
public class pageLoadStrategy {
public static void main(String[] args) {
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setPageLoadStrategy(PageLoadStrategy.NORMAL);
WebDriver driver = new ChromeDriver(chromeOptions);
try {
// Navigate to Url
driver.get("https://google.com");
} finally {
driver.quit();
}
}
}
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
options.page_load_strategy = 'normal'
driver = webdriver.Chrome(options=options)
driver.get("http://www.google.com")
driver.quit()
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
namespace pageLoadStrategy {
class pageLoadStrategy {
public static void Main(string[] args) {
var chromeOptions = new ChromeOptions();
chromeOptions.PageLoadStrategy = PageLoadStrategy.Normal;
IWebDriver driver = new ChromeDriver(chromeOptions);
try {
driver.Navigate().GoToUrl("https://example.com");
} finally {
driver.Quit();
}
}
}
}
require 'selenium-webdriver'
options = Selenium::WebDriver::Options.chrome
options.page_load_strategy = :normal
driver = Selenium::WebDriver.for :chrome, options: options
driver.get('https://www.google.com')
it('Navigate using normal page loading strategy', async function () {
let driver = await env
.builder()
.setChromeOptions(options.setPageLoadStrategy('normal'))
.build();
await driver.get('https://www.google.com');
import org.openqa.selenium.PageLoadStrategy
import org.openqa.selenium.chrome.ChromeDriver
import org.openqa.selenium.chrome.ChromeOptions
fun main() {
val chromeOptions = ChromeOptions()
chromeOptions.setPageLoadStrategy(PageLoadStrategy.NORMAL)
val driver = ChromeDriver(chromeOptions)
try {
driver.get("https://www.google.com")
}
finally {
driver.quit()
}
}
WebDriver一直等到 DOMContentLoaded 事件触发并返回.
import org.openqa.selenium.PageLoadStrategy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.chrome.ChromeDriver;
public class pageLoadStrategy {
public static void main(String[] args) {
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setPageLoadStrategy(PageLoadStrategy.EAGER);
WebDriver driver = new ChromeDriver(chromeOptions);
try {
// Navigate to Url
driver.get("https://google.com");
} finally {
driver.quit();
}
}
}
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
options.page_load_strategy = 'eager'
driver = webdriver.Chrome(options=options)
driver.get("http://www.google.com")
driver.quit()
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
namespace pageLoadStrategy {
class pageLoadStrategy {
public static void Main(string[] args) {
var chromeOptions = new ChromeOptions();
chromeOptions.PageLoadStrategy = PageLoadStrategy.Eager;
IWebDriver driver = new ChromeDriver(chromeOptions);
try {
driver.Navigate().GoToUrl("https://example.com");
} finally {
driver.Quit();
}
}
}
}
require 'selenium-webdriver'
options = Selenium::WebDriver::Options.chrome
options.page_load_strategy = :eager
driver = Selenium::WebDriver.for :chrome, options: options
driver.get('https://www.google.com')
it('Navigate using eager page loading strategy', async function () {
let driver = await env
.builder()
.setChromeOptions(options.setPageLoadStrategy('eager'))
.build();
await driver.get('https://www.google.com');
import org.openqa.selenium.PageLoadStrategy
import org.openqa.selenium.chrome.ChromeDriver
import org.openqa.selenium.chrome.ChromeOptions
fun main() {
val chromeOptions = ChromeOptions()
chromeOptions.setPageLoadStrategy(PageLoadStrategy.EAGER)
val driver = ChromeDriver(chromeOptions)
try {
driver.get("https://www.google.com")
}
finally {
driver.quit()
}
}
WebDriver 仅等待初始页面已下载.
import org.openqa.selenium.PageLoadStrategy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.chrome.ChromeDriver;
public class pageLoadStrategy {
public static void main(String[] args) {
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setPageLoadStrategy(PageLoadStrategy.NONE);
WebDriver driver = new ChromeDriver(chromeOptions);
try {
// Navigate to Url
driver.get("https://google.com");
} finally {
driver.quit();
}
}
}
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
options.page_load_strategy = 'none'
driver = webdriver.Chrome(options=options)
driver.get("http://www.google.com")
driver.quit()
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
namespace pageLoadStrategy {
class pageLoadStrategy {
public static void Main(string[] args) {
var chromeOptions = new ChromeOptions();
chromeOptions.PageLoadStrategy = PageLoadStrategy.None;
IWebDriver driver = new ChromeDriver(chromeOptions);
try {
driver.Navigate().GoToUrl("https://example.com");
} finally {
driver.Quit();
}
}
}
}
require 'selenium-webdriver'
options = Selenium::WebDriver::Options.chrome
options.page_load_strategy = :none
driver = Selenium::WebDriver.for :chrome, options: options
driver.get('https://www.google.com')
it('Navigate using none page loading strategy', async function () {
let driver = await env
.builder()
.setChromeOptions(options.setPageLoadStrategy('none'))
.build();
await driver.get('https://www.google.com');
import org.openqa.selenium.PageLoadStrategy
import org.openqa.selenium.chrome.ChromeDriver
import org.openqa.selenium.chrome.ChromeOptions
fun main() {
val chromeOptions = ChromeOptions()
chromeOptions.setPageLoadStrategy(PageLoadStrategy.NONE)
val driver = ChromeDriver(chromeOptions)
try {
driver.get("https://www.google.com")
}
finally {
driver.quit()
}
}
这标识了远端的操作系统,
获取 platformName
将返回操作系统的名称.
在基于云的供应者中,
设置 platformName
将在远程端设置操作系统.
此功能检查在会话期间导航时
是否使用了过期的 (或) 无效的 TLS Certificate
.
如果将功能设置为 false
,
则页面浏览遇到任何域证书问题时,
将返回insecure certificate error .
如果设置为 true
, 则浏览器将信任无效证书.
默认情况下, 此功能将信任所有自签名证书.
设置后, acceptInsecureCerts
功能将在整个会话中生效.
WebDriver session
具有一定的 session timeout
间隔,
在此间隔内, 用户可以控制执行脚本或从浏览器检索信息的行为.
每个会话超时都配置有不同 timeouts
的组合,
如下所述:
指定在当前浏览上下文中, 中断正在执行脚本的时机. WebDriver创建新会话时, 将设置默认的超时时间为 30,000 .
指定在当前浏览上下文中, 加载网页的时间间隔. WebDriver创建新会话时, 默认设置超时时间为 300,000 . 如果页面加载限制了给定 (或默认) 的时间范围, 则该脚本将被 TimeoutException 停止.
指定在定位元素时, 等待隐式元素定位策略的时间. WebDriver创建新会话时, 将设置默认超时时间为 0 .
指定当前会话 user prompt handler
的状态.
默认为 dismiss and notify state .
这定义了在远端出现用户提示时必须采取的措施.
该行为由unhandledPromptBehavior
功能定义,
具有以下状态:
新功能用于是否对 类型为文件的输入(input type=file) 元素进行严格的交互性检查. 默认关闭严格性检查, 在将 元素的Send Keys 方法作用于隐藏的文件上传时, 会有控制方面的行为区别.
代理服务器充当客户端和服务器之间的请求中介. 简述而言, 流量将通过代理服务器流向您请求的地址, 然后返回.
使用代理服务器用于Selenium的自动化脚本, 可能对以下方面有益:
如果您在公司环境中, 并且浏览器无法连接到URL, 则最有可能是因为环境, 需要借助代理进行访问.
Selenium WebDriver提供了如下设置代理的方法
import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
public class proxyTest {
public static void main(String[] args) {
Proxy proxy = new Proxy();
proxy.setHttpProxy("<HOST:PORT>");
ChromeOptions options = new ChromeOptions();
options.setCapability("proxy", proxy);
WebDriver driver = new ChromeDriver(options);
driver.get("https://www.google.com/");
driver.manage().window().maximize();
driver.quit();
}
}
from selenium import webdriver
PROXY = "<HOST:PORT>"
webdriver.DesiredCapabilities.FIREFOX['proxy'] = {
"httpProxy": PROXY,
"ftpProxy": PROXY,
"sslProxy": PROXY,
"proxyType": "MANUAL",
}
with webdriver.Firefox() as driver:
# Open URL
driver.get("https://selenium.dev")
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
public class ProxyTest{
public static void Main() {
ChromeOptions options = new ChromeOptions();
Proxy proxy = new Proxy();
proxy.Kind = ProxyKind.Manual;
proxy.IsAutoDetect = false;
proxy.SslProxy = "<HOST:PORT>";
options.Proxy = proxy;
options.AddArgument("ignore-certificate-errors");
IWebDriver driver = new ChromeDriver(options);
driver.Navigate().GoToUrl("https://www.selenium.dev/");
}
}
# this code was written with Selenium 4
proxy = Selenium::WebDriver::Proxy.new(http: '<HOST:PORT>')
cap = Selenium::WebDriver::Remote::Capabilities.chrome(proxy: proxy)
driver = Selenium::WebDriver.for(:chrome, capabilities: cap)
driver.get('http://google.com')
let webdriver = require('selenium-webdriver');
let chrome = require('selenium-webdriver/chrome');
let proxy = require('selenium-webdriver/proxy');
let opts = new chrome.Options();
(async function example() {
opts.setProxy(proxy.manual({http: '<HOST:PORT>'}));
let driver = new webdriver.Builder()
.forBrowser('chrome')
.setChromeOptions(opts)
.build();
try {
await driver.get("https://selenium.dev");
}
finally {
await driver.quit();
}
}());
import org.openqa.selenium.Proxy
import org.openqa.selenium.WebDriver
import org.openqa.selenium.chrome.ChromeDriver
import org.openqa.selenium.chrome.ChromeOptions
class proxyTest {
fun main() {
val proxy = Proxy()
proxy.setHttpProxy("<HOST:PORT>")
val options = ChromeOptions()
options.setCapability("proxy", proxy)
val driver: WebDriver = ChromeDriver(options)
driver["https://www.google.com/"]
driver.manage().window().maximize()
driver.quit()
}
}
服务类用于管理驱动程序的启动和停止. 它们不适用于远程驱动程序.
允许您在每次发送特定 Selenium 命令时执行自定义操作
允许您为HTTP库设置各种参数.
您可以如本地一样, 使用远程WebDriver. 主要区别在于需要配置远程WebDriver, 以便可以在不同的计算机上运行测试.
远程WebDriver由两部分组成:客户端和服务端. 客户端是您的WebDriver测试,而服务端仅仅是可以被托管于任何现代Java EE应用服务器的Java Servlet.
要运行远程WebDriver客户端, 我们首先需要连接到RemoteWebDriver. 为此, 我们将URL指向运行测试的服务器的地址. 为了自定义我们的配置, 我们设置了既定的功能. 下面是一个实例化样例, 其指向我们的远程Web服务器 www.example.com 的远程WebDriver对象, 并在Firefox上运行测试.
FirefoxOptions firefoxOptions = new FirefoxOptions();
WebDriver driver = new RemoteWebDriver(new URL("http://www.example.com"), firefoxOptions);
driver.get("http://www.google.com");
driver.quit();
from selenium import webdriver
firefox_options = webdriver.FirefoxOptions()
driver = webdriver.Remote(
command_executor='http://www.example.com',
options=firefox_options
)
driver.get("http://www.google.com")
driver.quit()
FirefoxOptions firefoxOptions = new FirefoxOptions();
IWebDriver driver = new RemoteWebDriver(new Uri("http://www.example.com"), firefoxOptions);
driver.Navigate().GoToUrl("http://www.google.com");
driver.Quit();
require 'selenium-webdriver'
driver = Selenium::WebDriver.for :remote, url: "http://www.example.com", desired_capabilities: :firefox
driver.get "http://www.google.com"
driver.close
const { Builder, Capabilities } = require("selenium-webdriver");
var capabilities = Capabilities.firefox();
(async function helloSelenium() {
let driver = new Builder()
.usingServer("http://example.com")
.withCapabilities(capabilities)
.build();
try {
await driver.get('http://www.google.com');
} finally {
await driver.quit();
}
})();
firefoxOptions = FirefoxOptions()
driver: WebDriver = new RemoteWebDriver(new URL("http://www.example.com"), firefoxOptions)
driver.get("http://www.google.com")
driver.quit()
为了进一步自定义测试配置, 我们可以添加其他既定的功能.
例如, 假设您想使用Chrome版本67 在Windows XP上运行Chrome:
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setCapability("browserVersion", "67");
chromeOptions.setCapability("platformName", "Windows XP");
WebDriver driver = new RemoteWebDriver(new URL("http://www.example.com"), chromeOptions);
driver.get("http://www.google.com");
driver.quit();
from selenium import webdriver
chrome_options = webdriver.ChromeOptions()
chrome_options.set_capability("browserVersion", "67")
chrome_options.set_capability("platformName", "Windows XP")
driver = webdriver.Remote(
command_executor='http://www.example.com',
options=chrome_options
)
driver.get("http://www.google.com")
driver.quit()
var chromeOptions = new ChromeOptions();
chromeOptions.BrowserVersion = "67";
chromeOptions.PlatformName = "Windows XP";
IWebDriver driver = new RemoteWebDriver(new Uri("http://www.example.com"), chromeOptions);
driver.Navigate().GoToUrl("http://www.google.com");
driver.Quit();
caps = Selenium::WebDriver::Remote::Capabilities.chrome
caps.platform = Windows XP
caps.version = 67
driver = Selenium::WebDriver.for :remote, :url => "http://www.example.com", :desired_capabilities => caps
const { Builder } = require("selenium-webdriver");
const chrome = require("selenium-webdriver/chrome");
let opts = new chrome.Options();
opts.setAcceptInsecureCerts(true);
opts.setBrowserVersion('67');
opts.setPlatform('Windows XP');
(async function helloSelenium() {
let driver = new Builder()
.usingServer("http://example.com")
.forBrowser('chrome')
.setChromeOptions(opts)
.build();
try {
await driver.get('http://www.google.com');
}
finally {
await driver.quit();
}
})();
val chromeOptions = ChromeOptions()
chromeOptions.setCapability("browserVersion", "67")
chromeOptions.setCapability("platformName", "Windows XP")
val driver: WebDriver = new RemoteWebDriver(new URL("http://www.example.com"), chromeOptions)
driver.get("http://www.google.com")
driver.quit()
本地文件检测器允许将文件从客户端计算机传输到远程服务器. 例如, 如果测试需要将文件上传到Web应用程序, 则远程WebDriver可以在运行时 将文件从本地计算机自动传输到远程Web服务器. 这允许从运行测试的远程计算机上载文件. 默认情况下未启用它, 可以通过以下方式启用:
driver.setFileDetector(new LocalFileDetector());
from selenium.webdriver.remote.file_detector import LocalFileDetector
driver.file_detector = LocalFileDetector()
var allowsDetection = this.driver as IAllowsFileDetection;
if (allowsDetection != null)
{
allowsDetection.FileDetector = new LocalFileDetector();
}
@driver.file_detector = lambda do |args|
# args => ["/path/to/file"]
str = args.first.to_s
str if File.exist?(str)
end
var remote = require('selenium-webdriver/remote');
driver.setFileDetector(new remote.FileDetector);
driver.fileDetector = LocalFileDetector()
定义上述代码后, 您可以通过以下方式在测试中上传文件:
driver.get("http://sso.dev.saucelabs.com/test/guinea-file-upload");
WebElement upload = driver.findElement(By.id("myfile"));
upload.sendKeys("/Users/sso/the/local/path/to/darkbulb.jpg");
driver.get("http://sso.dev.saucelabs.com/test/guinea-file-upload")
driver.find_element(By.ID, "myfile").send_keys("/Users/sso/the/local/path/to/darkbulb.jpg")
driver.Navigate().GoToUrl("http://sso.dev.saucelabs.com/test/guinea-file-upload");
IWebElement upload = driver.FindElement(By.Id("myfile"));
upload.SendKeys(@"/Users/sso/the/local/path/to/darkbulb.jpg");
@driver.navigate.to "http://sso.dev.saucelabs.com/test/guinea-file-upload"
element = @driver.find_element(:id, 'myfile')
element.send_keys "/Users/sso/SauceLabs/sauce/hostess/maitred/maitred/public/images/darkbulb.jpg"
driver.get("http://sso.dev.saucelabs.com/test/guinea-file-upload");
var upload = driver.findElement(By.id("myfile"));
upload.sendKeys("/Users/sso/the/local/path/to/darkbulb.jpg");
driver.get("http://sso.dev.saucelabs.com/test/guinea-file-upload")
val upload: WebElement = driver.findElement(By.id("myfile"))
upload.sendKeys("/Users/sso/the/local/path/to/darkbulb.jpg")
此功能仅适用于Java客户端绑定 (Beta版以后). 远程WebDriver客户端向Selenium网格服务器发送请求, 后者将请求传递给WebDriver. 应该在服务器端和客户端启用跟踪, 以便端到端地追踪HTTP请求. 两端都应该有一个指向可视化框架的追踪导出器设置. 默认情况下, 对客户端和服务器都启用追踪. 若设置可视化框架Jaeger UI及Selenium Grid 4, 请参阅所需版本的追踪设置 .
对于客户端设置, 请执行以下步骤.
可以使用Maven安装追踪导出器的外部库. 在项目pom.xml中添加 opentelemetry-exporter-jaeger 和 grpc-netty 的依赖项:
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-exporter-jaeger</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-netty</artifactId>
<version>1.35.0</version>
</dependency>
System.setProperty("otel.traces.exporter", "jaeger");
System.setProperty("otel.exporter.jaeger.endpoint", "http://localhost:14250");
System.setProperty("otel.resource.attributes", "service.name=selenium-java-client");
ImmutableCapabilities capabilities = new ImmutableCapabilities("browserName", "chrome");
WebDriver driver = new RemoteWebDriver(new URL("http://www.example.com"), capabilities);
driver.get("http://www.google.com");
driver.quit();
有关所需Selenium版本 及其外部依赖关系版本等更多信息, 请参阅追踪设置 .
更多信息请访问:
Some browser specific functionalities require workarounds as mentioned in this issue.
每个浏览器都有定制和特有的功能。
默认情况下,Selenium 4与Chrome v75及更高版本兼容. 但是请注意Chrome浏览器的版本与chromedriver的主版本需要匹配.
所有浏览器的通用功能请看这 Options page.
Chrome浏览器的特有功能可以在谷歌的页面找到: Capabilities & ChromeOptions
基于默认选项的Chrome浏览器会话看起来是这样:
ChromeOptions options = new ChromeOptions();
driver = new ChromeDriver(options);
options = ChromeOptions()
driver = webdriver.Chrome(options=options)
var options = new ChromeOptions();
var driver = new ChromeDriver(options);
options = Selenium::WebDriver::Options.chrome(args: ['--headless=new'])
const Options = new Chrome.Options();
let driver = await env
.builder()
.setChromeOptions(Options)
.build();
下面是一些不同功能的常见示例:
args
参数是启动浏览器时输入的浏览器命令行参数.
常用的参数包括 --start-maximized
和 --headless=new
添加一个参数到选项中:
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless=new");
driver = new ChromeDriver(options);
chrome_options = ChromeOptions()
chrome_options.add_argument("--headless=new")
var options = new ChromeOptions();
options.AddArgument("--headless=new");
var driver = new ChromeDriver(options);
options = Selenium::WebDriver::Options.chrome(args: ['--headless=new'])
let driver = await env
.builder()
.setChromeOptions(options.addArguments('--headless=new'))
.build();
binary
参数接收一个使用浏览器的备用路径,通过这个参数你可以使用chromedriver 去驱动各种基于Chromium 内核的浏览器.
添加一个浏览器地址到选项中:
let driver = await env
.builder()
.setChromeOptions(options.setChromeBinaryPath(`Path to chrome binary`))
.build();
extensions
参数接受crx文件. As for unpacked directories,
please use the load-extension
argument instead, as mentioned in
this post.
添加一个扩展程序到选项中:
将 detach
参数设置为true将在驱动过程结束后保持浏览器的打开状态.
添加一个布尔值到选项中:
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("detach", true);
driver = new ChromeDriver(options);
chrome_options = ChromeOptions()
chrome_options.add_experimental_option("detach", True)
options = Selenium::WebDriver::Options.chrome(detach: true)
let driver = await env
.builder()
.setChromeOptions(options.detachDriver(true))
.build();
Chrome 添加了各种参数,如果你不希望添加某些参数,可以将其传入 excludeSwitches
.
一个常见的例子是重新打开弹出窗口阻止程序.
设置排除参数至选项中:
chrome_options = ChromeOptions()
chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])
options = Selenium::WebDriver::Options.chrome(exclude_switches: ['enable-automation'])
let driver = await env
.builder()
.setChromeOptions(options.excludeSwitches('enable-automation'))
.build();
你可以驱动 Chrome Cast 设备,包括共享选项卡
您可以模拟各种网络条件.
The following examples are for local webdrivers. For remote webdrivers, please refer to the Remote WebDriver page.
See the Chrome DevTools section for more information about using Chrome DevTools
微软Edge是用Chromium实现的,最早支持版本是v79. 与Chrome类似, Edge驱动的主版本号必须与Edge浏览器的主要版本匹配.
在 Chrome 页面 上找到的所有capabilities和选项也适用于Edge.
使用基本定义的选项启动 Edge 会话如下所示:
EdgeOptions options = new EdgeOptions();
driver = new EdgeDriver(options);
options = EdgeOptions()
driver = webdriver.Edge(options=options)
var options = new EdgeOptions();
var driver = new EdgeDriver(options);
options = Selenium::WebDriver::Options.edge
@driver = Selenium::WebDriver.for :edge, options: options
let options = new edge.Options();
driver = await env.builder()
.setEdgeOptions(options)
.setEdgeService(new edge.ServiceBuilder(edgedriver.binPath()))
.build();
The args
parameter is for a list of Command Line Switches
used when starting the browser.
Commonly used args include --start-maximized
and --headless=new
Add an argument to options:
EdgeOptions options = new EdgeOptions();
options.addArguments("--headless=new");
driver = new EdgeDriver(options);
options = EdgeOptions()
options.add_argument("--headless=new")
var options = new EdgeOptions();
options.AddArgument("--headless=new");
options = Selenium::WebDriver::Options.edge(args: ['--headless=new'])
@driver = Selenium::WebDriver.for :edge, options: options
微软Edge可以被"Internet Explorer兼容模式"驱动, 该模式使用Internet Explorer驱动类与微软Edge结合使用. 阅读 Internet Explorer 页面 了解更多详情.
Selenium 4 requires Firefox 78 or greater. It is recommended to always use the latest version of geckodriver.
Capabilities common to all browsers are described on the Options page.
Capabilities unique to Firefox can be found at Mozilla’s page for firefoxOptions
Starting a Firefox session with basic defined options looks like this:
FirefoxOptions options = new FirefoxOptions();
driver = new FirefoxDriver(options);
options = FirefoxOptions()
driver = webdriver.Firefox(options=options)
var options = new FirefoxOptions();
driver = new FirefoxDriver(options);
options = Selenium::WebDriver::Options.firefox
@driver = Selenium::WebDriver.for :firefox, options: options
let options = new firefox.Options();
driver = await env.builder()
.setFirefoxOptions(options)
.build();
Here are a few common use cases with different capabilities:
The args
parameter is for a list of Command line switches used when starting the browser.
Commonly used args include -headless
and "-profile", "/path/to/profile"
Add an argument to options:
FirefoxOptions options = new FirefoxOptions();
options.addArguments("-headless");
options=Options()
options.add_argument("-profile")
options.add_argument("/path/to/profile")
var options = new FirefoxOptions();
options.AddArgument("-headless");
driver = new FirefoxDriver(options);
let driver = new Builder()
.setFirefoxOptions(options.addArguments('--headless'))
.build();
The binary
parameter takes the path of an alternate location of browser to use. For example, with this parameter you can
use geckodriver to drive Firefox Nightly instead of the production version when both are present on your computer.
Add a browser location to options:
There are several ways to work with Firefox profiles
FirefoxProfile profile = new FirefoxProfile();
FirefoxOptions options = new FirefoxOptions();
options.setProfile(profile);
driver = new RemoteWebDriver(options);
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
options=Options()
firefox_profile = FirefoxProfile()
firefox_profile.set_preference("javascript.enabled", False)
options.profile = firefox_profile
var options = new FirefoxOptions();
var profile = new FirefoxProfile();
options.Profile = profile;
var driver = new RemoteWebDriver(options);
profile = Selenium::WebDriver::Firefox::Profile.new
profile['browser.download.dir'] = "/tmp/webdriver-downloads"
options = Selenium::WebDriver::Firefox::Options.new(profile: profile)
driver = Selenium::WebDriver.for :firefox, options: options
const { Builder } = require("selenium-webdriver");
const firefox = require('selenium-webdriver/firefox');
const options = new firefox.Options();
let profile = '/path to custom profile';
options.setProfile(profile);
const driver = new Builder()
.forBrowser('firefox')
.setFirefoxOptions(options)
.build();
val options = FirefoxOptions()
options.profile = FirefoxProfile()
driver = RemoteWebDriver(options)
Unlike Chrome, Firefox extensions are not added as part of capabilities as mentioned in this issue, they are created after starting the driver.
The following examples are for local webdrivers. For remote webdrivers, please refer to the Remote WebDriver page.
A signed xpi file you would get from Mozilla Addon page
Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
driver.installExtension(xpiPath);
path = os.path.abspath("tests/extensions/webextensions-selenium-example.xpi")
driver.install_addon(path)
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
string extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.xpi");
driver.InstallAddOnFromFile(Path.GetFullPath(extensionFilePath));
driver.install_addon(extension_file_path)
Uninstalling an addon requires knowing its id. The id can be obtained from the return value when installing the add-on.
Path xpiPath = Paths.get("src/test/resources/extensions/selenium-example.xpi");
String id = driver.installExtension(xpiPath);
driver.uninstallExtension(id);
path = os.path.abspath("tests/extensions/webextensions-selenium-example.xpi")
id = driver.install_addon(path)
driver.uninstall_addon(id)
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
string extensionFilePath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example.xpi");
string extensionId = driver.InstallAddOnFromFile(Path.GetFullPath(extensionFilePath));
driver.UninstallAddOn(extensionId);
extension_id = driver.install_addon(extension_file_path)
driver.uninstall_addon(extension_id)
When working with an unfinished or unpublished extension, it will likely not be signed. As such, it can only be installed as “temporary.” This can be done by passing in either a zip file or a directory, here’s an example with a directory:
Path path = Paths.get("src/test/resources/extensions/selenium-example");
driver.installExtension(path, true);
path = os.path.abspath("tests/extensions/webextensions-selenium-example/")
driver.install_addon(path, temporary=True)
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
string extensionDirPath = Path.Combine(baseDir, "../../../Extensions/webextensions-selenium-example/");
driver.InstallAddOnFromDirectory(Path.GetFullPath(extensionDirPath), true);
The following examples are for local webdrivers. For remote webdrivers, please refer to the Remote WebDriver page.
The following examples are for local webdrivers. For remote webdrivers, please refer to the Remote WebDriver page.
As of June 2022, Selenium officially no longer supports standalone Internet Explorer. The Internet Explorer driver still supports running Microsoft Edge in “IE Compatibility Mode.”
The IE Driver is the only driver maintained by the Selenium Project directly. While binaries for both the 32-bit and 64-bit versions of Internet Explorer are available, there are some known limitations with the 64-bit driver. As such it is recommended to use the 32-bit driver.
Additional information about using Internet Explorer can be found on the IE Driver Server page
Starting a Microsoft Edge browser in Internet Explorer Compatibility mode with basic defined options looks like this:
InternetExplorerOptions options = new InternetExplorerOptions();
driver = new InternetExplorerDriver(options);
options = InternetExplorerOptions()
driver = webdriver.Ie(options=options)
var options = new InternetExplorerOptions();
var driver = new InternetExplorerDriver(options);
options = Selenium::WebDriver::Options.ie
@driver = Selenium::WebDriver.for :ie, options: options
let driver = await new Builder()
.forBrowser('internet explorer')
.setIEOptions(options)
.build();
val options = InternetExplorerOptions()
val driver = InternetExplorerDriver(options)
As of Internet Explorer Driver v4.5.0:
As of Internet Explorer Driver v4.7.0:
Here are a few common use cases with different capabilities:
在某些环境中, 当打开文件上传对话框时, Internet Explorer可能会超时. IEDriver的默认超时为1000毫秒, 但您可以使用fileUploadDialogTimeout功能来增加超时时间.
InternetExplorerOptions options = new InternetExplorerOptions();
options.waitForUploadDialogUpTo(Duration.ofSeconds(2));
WebDriver driver = new RemoteWebDriver(options);
from selenium import webdriver
options = webdriver.IeOptions()
options.file_upload_dialog_timeout = 2000
driver = webdriver.Ie(options=options)
driver.get("http://www.google.com")
driver.quit()
var options = new InternetExplorerOptions();
options.FileUploadDialogTimeout = TimeSpan.FromMilliseconds(2000);
var driver = new RemoteWebDriver(options);
options = Selenium::WebDriver::IE::Options.new
options.file_upload_dialog_timeout = 2000
driver = Selenium::WebDriver.for(:ie, options: options)
const ie = require('selenium-webdriver/ie');
let options = new ie.Options().fileUploadDialogTimeout(2000);
let driver = await Builder()
.setIeOptions(options)
.build();
val options = InternetExplorerOptions()
options.waitForUploadDialogUpTo(Duration.ofSeconds(2))
val driver = RemoteWebDriver(options)
设置为 true
时,
此功能将清除InternetExplorer所有正在运行实例的
缓存, 浏览器历史记录和Cookies
(包括手动启动或由驱动程序启动的实例) .
默认情况下,此设置为 false
.
使用此功能将导致启动浏览器时性能下降, 因为驱动程序将等待直到缓存清除后再启动IE浏览器.
此功能接受一个布尔值作为参数.
InternetExplorerOptions options = new InternetExplorerOptions();
options.destructivelyEnsureCleanSession();
WebDriver driver = new RemoteWebDriver(options);
from selenium import webdriver
options = webdriver.IeOptions()
options.ensure_clean_session = True
driver = webdriver.Ie(options=options)
driver.get("http://www.google.com")
driver.quit()
var options = new InternetExplorerOptions();
options.EnsureCleanSession = true;
var driver = new RemoteWebDriver(options);
options = Selenium::WebDriver::IE::Options.new
options.ensure_clean_session = true
driver = Selenium::WebDriver.for(:ie, options: options)
const ie = require('selenium-webdriver/ie');
let options = new ie.Options().ensureCleanSession(true);
let driver = await Builder()
.setIeOptions(options)
.build();
val options = InternetExplorerOptions()
options.destructivelyEnsureCleanSession()
val driver = RemoteWebDriver(options)
InternetExplorer驱动程序期望浏览器的缩放级别为100%, 否则驱动程序将可能抛出异常. 通过将 ignoreZoomSetting 设置为 true, 可以禁用此默认行为.
此功能接受一个布尔值作为参数.
InternetExplorerOptions options = new InternetExplorerOptions();
options.ignoreZoomSettings();
WebDriver driver = new RemoteWebDriver(options);
from selenium import webdriver
options = webdriver.IeOptions()
options.ignore_zoom_level = True
driver = webdriver.Ie(options=options)
driver.get("http://www.google.com")
driver.quit()
var options = new InternetExplorerOptions();
options.IgnoreZoomLevel = true;
var driver = new RemoteWebDriver(options);
options = Selenium::WebDriver::IE::Options.new
options.ignore_zoom_level = true
driver = Selenium::WebDriver.for(:ie, options: options)
const ie = require('selenium-webdriver/ie');
let options = new ie.Options().ignoreZoomSetting(true);
let driver = await Builder()
.setIeOptions(options)
.build();
val options = InternetExplorerOptions()
options.ignoreZoomSettings()
val driver = RemoteWebDriver(options)
启动新的IE会话时是否跳过 保护模式 检查.
如果未设置, 并且所有区域的 保护模式 设置都不同, 则驱动程序将可能引发异常.
如果将功能设置为 true
,
则测试可能会变得不稳定, 无响应, 或者浏览器可能会挂起.
但是, 到目前为止,
这仍然是第二好的选择,
并且第一选择应该 始终 是手动实际设置每个区域的保护模式设置.
如果用户正在使用此属性,
则只会给予 “尽力而为” 的支持.
此功能接受一个布尔值作为参数.
InternetExplorerOptions options = new InternetExplorerOptions();
options.introduceFlakinessByIgnoringSecurityDomains();
WebDriver driver = new RemoteWebDriver(options);
from selenium import webdriver
options = webdriver.IeOptions()
options.ignore_protected_mode_settings = True
driver = webdriver.Ie(options=options)
driver.get("http://www.google.com")
driver.quit()
var options = new InternetExplorerOptions();
options.IntroduceInstabilityByIgnoringProtectedModeSettings = true;
var driver = new RemoteWebDriver(options);
options = Selenium::WebDriver::IE::Options.new
options.ignore_protected_mode_settings = true
driver = Selenium::WebDriver.for(:ie, options: options)
const ie = require('selenium-webdriver/ie');
let options = new ie.Options().introduceFlakinessByIgnoringProtectedModeSettings(true);
let driver = await Builder()
.setIeOptions(options)
.build();
val options = InternetExplorerOptions()
options.introduceFlakinessByIgnoringSecurityDomains()
val driver = RemoteWebDriver(options)
设置为 true
时,
此功能将禁止IEDriverServer的诊断输出.
此功能接受一个布尔值作为参数.
InternetExplorerOptions options = new InternetExplorerOptions();
options.setCapability("silent", true);
WebDriver driver = new InternetExplorerDriver(options);
from selenium import webdriver
options = webdriver.IeOptions()
options.set_capability("silent", True)
driver = webdriver.Ie(options=options)
driver.get("http://www.google.com")
driver.quit()
InternetExplorerOptions options = new InternetExplorerOptions();
options.AddAdditionalInternetExplorerOption("silent", true);
IWebDriver driver = new InternetExplorerDriver(options);
<p><a href=https://github.com/SeleniumHQ/seleniumhq.github.io/tree/trunk/examples>
<span class="selenium-badge-code" data-toggle="tooltip" data-placement="right"
title="Code examples are added to the projects in examples directory of repo; see about section for contribution and style guids">Add Example</span></a></p>
const {Builder,By, Capabilities} = require('selenium-webdriver');
let caps = Capabilities.ie();
caps.set('silent', true);
(async function example() {
let driver = await new Builder()
.forBrowser('internet explorer')
.withCapabilities(caps)
.build();
try {
await driver.get('http://www.google.com/ncr');
}
finally {
await driver.quit();
}
})();
import org.openqa.selenium.Capabilities
import org.openqa.selenium.ie.InternetExplorerDriver
import org.openqa.selenium.ie.InternetExplorerOptions
fun main() {
val options = InternetExplorerOptions()
options.setCapability("silent", true)
val driver = InternetExplorerDriver(options)
try {
driver.get("https://google.com/ncr")
val caps = driver.getCapabilities()
println(caps)
} finally {
driver.quit()
}
}
Internet Explorer包含几个命令行选项, 使您可以进行故障排除和配置浏览器.
下面介绍了一些受支持的命令行选项
-private : 用于在私有浏览模式下启动IE. 这适用于IE 8和更高版本.
-k : 在kiosk模式下启动Internet Explorer. 浏览器在一个最大化的窗口中打开, 该窗口不显示地址栏, 导航按钮或状态栏.
-extoff : 在无附加模式下启动IE. 此选项专门用于解决浏览器加载项问题. 在IE 7和更高版本中均可使用.
注意: forceCreateProcessApi 应该启用命令行参数才能正常工作.
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.ie.InternetExplorerOptions;
public class ieTest {
public static void main(String[] args) {
InternetExplorerOptions options = new InternetExplorerOptions();
options.useCreateProcessApiToLaunchIe();
options.addCommandSwitches("-k");
InternetExplorerDriver driver = new InternetExplorerDriver(options);
try {
driver.get("https://google.com/ncr");
Capabilities caps = driver.getCapabilities();
System.out.println(caps);
} finally {
driver.quit();
}
}
}
from selenium import webdriver
options = webdriver.IeOptions()
options.add_argument('-private')
options.force_create_process_api = True
driver = webdriver.Ie(options=options)
driver.get("http://www.google.com")
driver.quit()
using System;
using OpenQA.Selenium;
using OpenQA.Selenium.IE;
namespace ieTest {
class Program {
static void Main(string[] args) {
InternetExplorerOptions options = new InternetExplorerOptions();
options.ForceCreateProcessApi = true;
options.BrowserCommandLineArguments = "-k";
IWebDriver driver = new InternetExplorerDriver(options);
driver.Url = "https://google.com/ncr";
}
}
}
require 'selenium-webdriver'
options = Selenium::WebDriver::IE::Options.new
options.force_create_process_api = true
options.add_argument('-k')
driver = Selenium::WebDriver.for(:ie, options: options)
begin
driver.get 'https://google.com'
puts(driver.capabilities.to_json)
ensure
driver.quit
end
const ie = require('selenium-webdriver/ie');
let options = new ie.Options();
options.addBrowserCommandSwitches('-k');
options.addBrowserCommandSwitches('-private');
options.forceCreateProcessApi(true);
driver = await env.builder()
.setIeOptions(options)
.build();
import org.openqa.selenium.Capabilities
import org.openqa.selenium.ie.InternetExplorerDriver
import org.openqa.selenium.ie.InternetExplorerOptions
fun main() {
val options = InternetExplorerOptions()
options.useCreateProcessApiToLaunchIe()
options.addCommandSwitches("-k")
val driver = InternetExplorerDriver(options)
try {
driver.get("https://google.com/ncr")
val caps = driver.getCapabilities()
println(caps)
} finally {
driver.quit()
}
}
强制使用CreateProcess API启动Internet Explorer. 默认值为false.
对于IE 8及更高版本, 此选项要求将 “TabProcGrowth” 注册表值设置为0.
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.ie.InternetExplorerOptions;
public class ieTest {
public static void main(String[] args) {
InternetExplorerOptions options = new InternetExplorerOptions();
options.useCreateProcessApiToLaunchIe();
InternetExplorerDriver driver = new InternetExplorerDriver(options);
try {
driver.get("https://google.com/ncr");
Capabilities caps = driver.getCapabilities();
System.out.println(caps);
} finally {
driver.quit();
}
}
}
from selenium import webdriver
options = webdriver.IeOptions()
options.force_create_process_api = True
driver = webdriver.Ie(options=options)
driver.get("http://www.google.com")
driver.quit()
using System;
using OpenQA.Selenium;
using OpenQA.Selenium.IE;
namespace ieTest {
class Program {
static void Main(string[] args) {
InternetExplorerOptions options = new InternetExplorerOptions();
options.ForceCreateProcessApi = true;
IWebDriver driver = new InternetExplorerDriver(options);
driver.Url = "https://google.com/ncr";
}
}
}
require 'selenium-webdriver'
options = Selenium::WebDriver::IE::Options.new
options.force_create_process_api = true
driver = Selenium::WebDriver.for(:ie, options: options)
begin
driver.get 'https://google.com'
puts(driver.capabilities.to_json)
ensure
driver.quit
end
const ie = require('selenium-webdriver/ie');
let options = new ie.Options();
options.forceCreateProcessApi(true);
driver = await env.builder()
.setIeOptions(options)
.build();
import org.openqa.selenium.Capabilities
import org.openqa.selenium.ie.InternetExplorerDriver
import org.openqa.selenium.ie.InternetExplorerOptions
fun main() {
val options = InternetExplorerOptions()
options.useCreateProcessApiToLaunchIe()
val driver = InternetExplorerDriver(options)
try {
driver.get("https://google.com/ncr")
val caps = driver.getCapabilities()
println(caps)
} finally {
driver.quit()
}
}
与Chromium和Firefox驱动不同, safari驱动随操作系统安装. 要在 Safari 上启用自动化, 请从终端运行以下命令:
safaridriver --enable
所有浏览器通用的Capabilities在选项页.
Safari独有的Capabilities可以在Apple的页面关于Safari的WebDriver 上找到
使用基本定义的选项启动 Safari 会话如下所示:
SafariOptions options = new SafariOptions();
driver = new SafariDriver(options);
options = SafariOptions()
driver = webdriver.Safari(options=options)
var options = new SafariOptions();
var driver = new SafariDriver(options);
options = Selenium::WebDriver::Options.safari
@driver = Selenium::WebDriver.for :safari, options: options
let driver = await env.builder()
.setSafariOptions(options)
.build();
val options = SafariOptions()
val driver = SafariDriver(options)
那些希望在iOS上自动化Safari的人可以参考 Appium project.
Apple provides a development version of their browser — Safari Technology Preview To use this version in your code:
WebDriver通常可以说有一个阻塞API。因为它是一个指示浏览器做什么的进程外库,而且web平台本质上是异步的,所以WebDriver不跟踪DOM的实时活动状态。这伴随着一些我们将在这里讨论的挑战。
根据经验,大多数由于使用Selenium和WebDriver而产生的间歇性问题都与浏览器和用户指令之间的 竞争条件 有关。例如,用户指示浏览器导航到一个页面,然后在试图查找元素时得到一个 no such element 的错误。
考虑下面的文档:
<!doctype html>
<meta charset=utf-8>
<title>Race Condition Example</title>
<script>
var initialised = false;
window.addEventListener("load", function() {
var newElement = document.createElement("p");
newElement.textContent = "Hello from JavaScript!";
document.body.appendChild(newElement);
initialised = true;
});
</script>
这个 WebDriver的说明可能看起来很简单:
driver.get("file:///race_condition.html");
WebElement element = driver.findElement(By.tagName("p"));
assertEquals(element.getText(), "Hello from JavaScript!");
driver.navigate("file:///race_condition.html")
el = driver.find_element(By.TAG_NAME, "p")
assert el.text == "Hello from JavaScript!"
driver.Navigate().GoToUrl("file:///race_condition.html");
IWebElement element = driver.FindElement(By.TagName("p"));
assertEquals(element.Text, "Hello from JavaScript!");
require 'selenium-webdriver'
driver = Selenium::WebDriver.for :firefox
begin
# Navigate to URL
driver.get 'file:///race_condition.html'
# Get and store Paragraph Text
search_form = driver.find_element(:css,'p').text
"Hello from JavaScript!".eql? search_form
ensure
driver.quit
end
await driver.get('file:///race_condition.html');
const element = driver.findElement(By.css('p'));
assert.strictEqual(await element.getText(), 'Hello from JavaScript!');
driver.get("file:///race_condition.html")
val element = driver.findElement(By.tagName("p"))
assert(element.text == "Hello from JavaScript!")
这里的问题是WebDriver中使用的默认页面加载策略页面加载策略听从document.readyState
在返回调用 navigate 之前将状态改为"complete"
。因为p
元素是在文档完成加载之后添加的,所以这个WebDriver脚本可能是间歇性的。它“可能”间歇性是因为无法做出保证说异步触发这些元素或事件不需要显式等待或阻塞这些事件。
幸运的是,WebElement接口上可用的正常指令集——例如 WebElement.click 和 WebElement.sendKeys—是保证同步的,因为直到命令在浏览器中被完成之前函数调用是不会返回的(或者回调是不会在回调形式的语言中触发的)。高级用户交互APIs,键盘和鼠标是例外的,因为它们被明确地设计为“按我说的做”的异步命令。
等待是在继续下一步之前会执行一个自动化任务来消耗一定的时间。
为了克服浏览器和WebDriver脚本之间的竞争问题,大多数Selenium客户都附带了一个 wait 包。在使用等待时,您使用的是通常所说的显式等待。
显示等待 是Selenium客户可以使用的命令式过程语言。它们允许您的代码暂停程序执行,或冻结线程,直到满足通过的 条件 。这个条件会以一定的频率一直被调用,直到等待超时。这意味着只要条件返回一个假值,它就会一直尝试和等待
由于显式等待允许您等待条件的发生,所以它们非常适合在浏览器及其DOM和WebDriver脚本之间同步状态。
为了弥补我们之前的错误指令集,我们可以使用等待来让 findElement 调用等待直到脚本中动态添加的元素被添加到DOM中:
WebDriver driver = new ChromeDriver();
driver.get("https://google.com/ncr");
driver.findElement(By.name("q")).sendKeys("cheese" + Keys.ENTER);
// Initialize and wait till element(link) became clickable - timeout in 10 seconds
WebElement firstResult = new WebDriverWait(driver, Duration.ofSeconds(10))
.until(ExpectedConditions.elementToBeClickable(By.xpath("//a/h3")));
// Print the first result
System.out.println(firstResult.getText());
from selenium.webdriver.support.wait import WebDriverWait
def document_initialised(driver):
return driver.execute_script("return initialised")
driver.navigate("file:///race_condition.html")
WebDriverWait(driver, timeout=10).until(document_initialised)
el = driver.find_element(By.TAG_NAME, "p")
assert el.text == "Hello from JavaScript!"
driver = new ChromeDriver();
driver.Url = "https://www.google.com/ncr";
driver.FindElement(By.Name("q")).SendKeys("cheese" + Keys.Enter);
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
IWebElement firstResult = wait.Until(e => e.FindElement(By.XPath("//a/h3")));
Console.WriteLine(firstResult.Text);
require 'selenium-webdriver'
driver = Selenium::WebDriver.for :firefox
wait = Selenium::WebDriver::Wait.new(:timeout => 10)
def document_initialised(driver)
driver.execute_script('return initialised')
end
begin
driver.get 'file:///race_condition.html'
wait.until{document_initialised driver}
search_form = driver.find_element(:css,'p').text
"Hello from JavaScript!".eql? search_form
ensure
driver.quit
end
const documentInitialised = () =>
driver.executeScript('return initialised');
await driver.get('file:///race_condition.html');
await driver.wait(() => documentInitialised(), 10000);
const element = driver.findElement(By.css('p'));
assert.strictEqual(await element.getText(), 'Hello from JavaScript!');
driver.get("https://google.com/ncr")
driver.findElement(By.name("q")).sendKeys("cheese" + Keys.ENTER)
// Initialize and wait till element(link) became clickable - timeout in 10 seconds
val firstResult = WebDriverWait(driver, Duration.ofSeconds(10))
.until(ExpectedConditions.elementToBeClickable(By.xpath("//a/h3")))
// Print the first result
println(firstResult.text)
我们将 条件 作为函数引用传递, 等待 将会重复运行直到其返回值为true。“truthful”返回值是在当前语言中计算为boolean true的任何值,例如字符串、数字、boolean、对象(包括 WebElement )或填充(非空)的序列或列表。这意味着 空列表 的计算结果为false。当条件为true且阻塞等待终止时,条件的返回值将成为等待的返回值。
有了这些知识,并且因为等待实用程序默认情况下会忽略 no such element 的错误,所以我们可以重构我们的指令使其更简洁:
WebElement foo = new WebDriverWait(driver, Duration.ofSeconds(3))
.until(driver -> driver.findElement(By.name("q")));
assertEquals(foo.getText(), "Hello from JavaScript!");
from selenium.webdriver.support.wait import WebDriverWait
driver.navigate("file:///race_condition.html")
el = WebDriverWait(driver, timeout=3).until(lambda d: d.find_element(By.TAG_NAME,"p"))
assert el.text == "Hello from JavaScript!"
using (var driver = new FirefoxDriver())
{
var foo = new WebDriverWait(driver, TimeSpan.FromSeconds(3))
.Until(drv => drv.FindElement(By.Name("q")));
Debug.Assert(foo.Text.Equals("Hello from JavaScript!"));
}
driver.get 'file:///race_condition.html'
wait = Selenium::WebDriver::Wait.new(:timeout => 10)
ele = wait.until { driver.find_element(css: 'p')}
foo = ele.text
assert_match foo, 'Hello from JavaScript'
let ele = await driver.wait(until.elementLocated(By.css('p')),10000);
let foo = await ele.getText();
assert(foo == "Hello from JavaScript");
driver.get("file:///race_condition.html")
val ele = WebDriverWait(driver, Duration.ofSeconds(10))
.until(ExpectedConditions.presenceOfElementLocated(By.tagName("p")))
assert(ele.text == "Hello from JavaScript!")
在这个示例中,我们传递了一个匿名函数(但是我们也可以像前面那样显式地定义它,以便重用它)。传递给我们条件的第一个,也是唯一的一个参数始终是对驱动程序对象 WebDriver 的引用。在多线程环境中,您应该小心操作传入条件的驱动程序引用,而不是外部范围中对驱动程序的引用。
因为等待将会吞没在没有找到元素时引发的 no such element 的错误,这个条件会一直重试直到找到元素为止。然后它将获取一个 WebElement 的返回值,并将其传递回我们的脚本。
如果条件失败,例如从未得到条件为真实的返回值,等待将会抛出/引发一个叫 timeout error 的错误/异常。
等待条件可以根据您的需要进行定制。有时候是没有必要等待缺省超时的全部范围,因为没有达到成功条件的代价可能很高。
等待允许你传入一个参数来覆盖超时:
new WebDriverWait(driver, Duration.ofSeconds(3)).until(ExpectedConditions.elementToBeClickable(By.xpath("//a/h3")));
WebDriverWait(driver, timeout=3).until(some_condition)
new WebDriverWait(driver, TimeSpan.FromSeconds(3)).Until(driver => driver.FindElement(By.Name("q")));
wait = Selenium::WebDriver::Wait.new(:timeout => 10)
wait.until { driver.find_element(:id, 'message').displayed? }
await driver.wait(until.elementLocated(By.id('foo')), 30000);
WebDriverWait(driver, Duration.ofSeconds(3)).until(ExpectedConditions.elementToBeClickable(By.xpath("//a/h3")))
由于必须同步DOM和指令是相当常见的情况,所以大多数客户端还附带一组预定义的 预期条件 。顾名思义,它们是为频繁等待操作预定义的条件。
不同的语言绑定提供的条件各不相同,但这只是其中一些:
您可以参考每个客户端绑定的API文档,以找到期望条件的详尽列表:
还有第二种区别于显示等待 类型的 隐式等待 。通过隐式等待,WebDriver在试图查找_任何_元素时在一定时间内轮询DOM。当网页上的某些元素不是立即可用并且需要一些时间来加载时是很有用的。
默认情况下隐式等待元素出现是禁用的,它需要在单个会话的基础上手动启用。将显式等待和隐式等待混合在一起会导致意想不到的结果,就是说即使元素可用或条件为真也要等待睡眠的最长时间。
警告: 不要混合使用隐式和显式等待。这样做会导致不可预测的等待时间。例如,将隐式等待设置为10秒,将显式等待设置为15秒,可能会导致在20秒后发生超时。
隐式等待是告诉WebDriver如果在查找一个或多个不是立即可用的元素时轮询DOM一段时间。默认设置为0,表示禁用。一旦设置好,隐式等待就被设置为会话的生命周期。
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
driver.get("http://somedomain/url_that_delays_loading");
WebElement myDynamicElement = driver.findElement(By.id("myDynamicElement"));
driver = Firefox()
driver.implicitly_wait(10)
driver.get("http://somedomain/url_that_delays_loading")
my_dynamic_element = driver.find_element(By.ID, "myDynamicElement")
IWebDriver driver = new ChromeDriver();
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);
driver.Url = "http://somedomain/url_that_delays_loading";
IWebElement dynamicElement = driver.FindElement(By.Name("dynamicElement"));
require 'selenium-webdriver'
driver = Selenium::WebDriver.for :firefox
driver.manage.timeouts.implicit_wait = 10
begin
driver.get 'http://somedomain/url_that_delays_loading'
search_form = driver.find_element(:id,'dynamic_element')
ensure
driver.quit
end
(async function(){
// Apply timeout for 10 seconds
await driver.manage().setTimeouts( { implicit: 10000 } );
// Navigate to url
await driver.get('http://somedomain/url_that_delays_loading');
let webElement = driver.findElement(By.id("myDynamicElement"));
}());
val driver = FirefoxDriver()
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10))
driver.get("http://somedomain/url_that_delays_loading")
val myDynamicElement = driver.findElement(By.id("myDynamicElement"))
流畅等待实例定义了等待条件的最大时间量,以及检查条件的频率。
用户可以配置等待来忽略等待时出现的特定类型的异常,例如在页面上搜索元素时出现的NoSuchElementException
。
// Waiting 30 seconds for an element to be present on the page, checking
// for its presence once every 5 seconds.
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(Duration.ofSeconds(30))
.pollingEvery(Duration.ofSeconds(5))
.ignoring(NoSuchElementException.class);
WebElement foo = wait.until(driver -> {
return driver.findElement(By.id("foo"));
});
driver = Firefox()
driver.get("http://somedomain/url_that_delays_loading")
wait = WebDriverWait(driver, timeout=10, poll_frequency=1, ignored_exceptions=[ElementNotVisibleException, ElementNotSelectableException])
element = wait.until(EC.element_to_be_clickable((By.XPATH, "//div")))
using (var driver = new FirefoxDriver())
{
WebDriverWait wait = new WebDriverWait(driver, timeout: TimeSpan.FromSeconds(30))
{
PollingInterval = TimeSpan.FromSeconds(5),
};
wait.IgnoreExceptionTypes(typeof(NoSuchElementException));
var foo = wait.Until(drv => drv.FindElement(By.Id("foo")));
}
require 'selenium-webdriver'
driver = Selenium::WebDriver.for :firefox
exception = Selenium::WebDriver::Error::NoSuchElementError
begin
driver.get 'http://somedomain/url_that_delays_loading'
wait = Selenium::WebDriver::Wait.new(timeout: 30, interval: 5, message: 'Timed out after 30 sec', ignore: exception)
foo = wait.until { driver.find_element(id: 'foo')}
ensure
driver.quit
end
const {Builder, until} = require('selenium-webdriver');
(async function example() {
let driver = await new Builder().forBrowser('firefox').build();
await driver.get('http://somedomain/url_that_delays_loading');
// Waiting 30 seconds for an element to be present on the page, checking
// for its presence once every 5 seconds.
let foo = await driver.wait(until.elementLocated(By.id('foo')), 30000, 'Timed out after 30 seconds', 5000);
})();
val wait = FluentWait<WebDriver>(driver)
.withTimeout(Duration.ofSeconds(30))
.pollingEvery(Duration.ofSeconds(3))
.ignoring(NoSuchElementException::class.java)
val foo = wait.until {it.findElement(By.id("foo")) }
大多数人的Selenium代码都涉及使用web元素.
当input元素为文件类型时, 文件上传对话框可以使用Selenium处理. 例如, 在这个网页中可以发现- https://the-internet.herokuapp.com/upload 我们需要一个可用的文件, 用于上传. 不同语言的文件上传的代码实现如下 -
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import io.github.bonigarcia.wdm.WebDriverManager;
class fileUploadDoc{
public static void main(String[] args) {
WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("https://the-internet.herokuapp.com/upload");
//we want to import selenium-snapshot file.
driver.findElement(By.id("file-upload")).sendKeys("selenium-snapshot.jpg");
driver.findElement(By.id("file-submit")).submit();
if(driver.getPageSource().contains("File Uploaded!")) {
System.out.println("file uploaded");
}
else{
System.out.println("file not uploaded");
}
driver.quit();
}
}
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
driver = webdriver.Chrome(ChromeDriverManager().install())
driver.implicitly_wait(10)
driver.get("https://the-internet.herokuapp.com/upload");
driver.find_element(By.ID,"file-upload").send_keys("selenium-snapshot.jpg")
driver.find_element(By.ID,"file-submit").submit()
if(driver.page_source.find("File Uploaded!")):
print("file upload success")
else:
print("file upload not successful")
driver.quit()
using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
namespace SeleniumDocumentation.SeleniumPRs
{
class FileUploadExample
{
static void Main(String[] args)
{
IWebDriver driver = new ChromeDriver();
try
{
// Navigate to Url
driver.Navigate().GoToUrl("https://the-internet.herokuapp.com/upload");
driver.FindElement(By.Id("file-upload")).SendKeys("selenium-snapshot.jpg");
driver.FindElement(By.Id("file-submit")).Submit();
if (driver.PageSource.Contains("File Uploaded!"))
{
Console.WriteLine("file uploaded");
}
else
{
Console.WriteLine("file not uploaded");
}
driver.Quit();
}
}
}
require 'selenium-webdriver'
driver = Selenium::WebDriver.for :chrome
driver.get("https://the-internet.herokuapp.com/upload")
driver.find_element(:id,"file-upload").send_keys("selenium-snapshot.jpg")
driver.find_element(:id,"file-submit").submit()
if driver.page_source().include? "File Uploaded!"
puts "file upload success"
else
puts "file upload not successful"
end
import {Builder,By} from "selenium-webdriver"
let driver = await new Builder().forBrowser('chrome').build()
await driver.get("https://the-internet.herokuapp.com/upload");
await driver.findElement(By.id("file-upload")).sendKeys("selenium-snapshot.jpg")
await driver.findElement(By.id("file-submit")).submit()
driver.getPageSource().then(result => {
if (result.indexOf("File Uploaded!")){
console.log("file upload success")
}else {
console.log("file upload not successful")
}
})
import org.openqa.selenium.By
import org.openqa.selenium.chrome.ChromeDriver
fun main() {
val driver = ChromeDriver()
driver.get("https://the-internet.herokuapp.com/upload")
driver.findElement(By.id("file-upload")).sendKeys("selenium-snapshot.jpg")
driver.findElement(By.id("file-submit")).submit()
if(driver.pageSource.contains("File Uploaded!")) {
println("file uploaded")
}
else{
println("file not uploaded")
}
}
所以上面的示例代码有助于我们理解 如何使用Selenium上传文件.
One of the most fundamental aspects of using Selenium is obtaining element references to work with. Selenium offers a number of built-in locator strategies to uniquely identify an element. There are many ways to use the locators in very advanced scenarios. For the purposes of this documentation, let’s consider this HTML snippet:
<ol id="vegetables">
<li class="potatoes">…
<li class="onions">…
<li class="tomatoes"><span>Tomato is a Vegetable</span>…
</ol>
<ul id="fruits">
<li class="bananas">…
<li class="apples">…
<li class="tomatoes"><span>Tomato is a Fruit</span>…
</ul>
Many locators will match multiple elements on the page. The singular find element method will return a reference to the first element found within a given context.
When the find element method is called on the driver instance, it returns a reference to the first element in the DOM that matches with the provided locator. This value can be stored and used for future element actions. In our example HTML above, there are two elements that have a class name of “tomatoes” so this method will return the element in the “vegetables” list.
WebElement vegetable = driver.findElement(By.className("tomatoes"));
vegetable = driver.find_element(By.CLASS_NAME, "tomatoes")
var vegetable = driver.FindElement(By.ClassName("tomatoes"));
vegetable = driver.find_element(class: 'tomatoes')
const vegetable = await driver.findElement(By.className('tomatoes'));
val vegetable: WebElement = driver.findElement(By.className("tomatoes"))
Rather than finding a unique locator in the entire DOM, it is often useful to narrow the search to the scope of another located element. In the above example there are two elements with a class name of “tomatoes” and it is a little more challenging to get the reference for the second one.
One solution is to locate an element with a unique attribute that is an ancestor of the desired element and not an ancestor of the undesired element, then call find element on that object:
WebElement fruits = driver.findElement(By.id("fruits"));
WebElement fruit = fruits.findElement(By.className("tomatoes"));
fruits = driver.find_element(By.ID, "fruits")
fruit = fruits.find_element(By.CLASS_NAME,"tomatoes")
IWebElement fruits = driver.FindElement(By.Id("fruits"));
IWebElement fruit = fruits.FindElement(By.ClassName("tomatoes"));
fruits = driver.find_element(id: 'fruits')
fruit = fruits.find_element(class: 'tomatoes')
const fruits = await driver.findElement(By.id('fruits'));
const fruit = fruits.findElement(By.className('tomatoes'));
val fruits = driver.findElement(By.id("fruits"))
val fruit = fruits.findElement(By.className("tomatoes"))
Java and C#WebDriver
, WebElement
and ShadowRoot
classes all implement a SearchContext
interface, which is
considered a role-based interface. Role-based interfaces allow you to determine whether a particular
driver implementation supports a given feature. These interfaces are clearly defined and try
to adhere to having only a single role of responsibility.
A nested lookup might not be the most effective location strategy since it requires two separate commands to be issued to the browser.
To improve the performance slightly, we can use either CSS or XPath to find this element in a single command. See the Locator strategy suggestions in our Encouraged test practices section.
For this example, we’ll use a CSS Selector:
WebElement fruit = driver.findElement(By.cssSelector("#fruits .tomatoes"));
fruit = driver.find_element(By.CSS_SELECTOR,"#fruits .tomatoes")
var fruit = driver.FindElement(By.CssSelector("#fruits .tomatoes"));
fruit = driver.find_element(css: '#fruits .tomatoes')
const fruit = await driver.findElement(By.css('#fruits .tomatoes'));
val fruit = driver.findElement(By.cssSelector("#fruits .tomatoes"))
There are several use cases for needing to get references to all elements that match a locator, rather than just the first one. The plural find elements methods return a collection of element references. If there are no matches, an empty list is returned. In this case, references to all fruits and vegetable list items will be returned in a collection.
List<WebElement> plants = driver.findElements(By.tagName("li"));
plants = driver.find_elements(By.TAG_NAME, "li")
IReadOnlyList<IWebElement> plants = driver.FindElements(By.TagName("li"));
plants = driver.find_elements(tag_name: 'li')
const plants = await driver.findElements(By.tagName('li'));
val plants: List<WebElement> = driver.findElements(By.tagName("li"))
Often you get a collection of elements but want to work with a specific element, which means you need to iterate over the collection and identify the one you want.
List<WebElement> elements = driver.findElements(By.tagName("li"));
for (WebElement element : elements) {
System.out.println("Paragraph text:" + element.getText());
}
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Firefox()
# Navigate to Url
driver.get("https://www.example.com")
# Get all the elements available with tag name 'p'
elements = driver.find_elements(By.TAG_NAME, 'p')
for e in elements:
print(e.text)
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using System.Collections.Generic;
namespace FindElementsExample {
class FindElementsExample {
public static void Main(string[] args) {
IWebDriver driver = new FirefoxDriver();
try {
// Navigate to Url
driver.Navigate().GoToUrl("https://example.com");
// Get all the elements available with tag name 'p'
IList < IWebElement > elements = driver.FindElements(By.TagName("p"));
foreach(IWebElement e in elements) {
System.Console.WriteLine(e.Text);
}
} finally {
driver.Quit();
}
}
}
}
require 'selenium-webdriver'
driver = Selenium::WebDriver.for :firefox
begin
# Navigate to URL
driver.get 'https://www.example.com'
# Get all the elements available with tag name 'p'
elements = driver.find_elements(:tag_name,'p')
elements.each { |e|
puts e.text
}
ensure
driver.quit
end
const {Builder, By} = require('selenium-webdriver');
(async function example() {
let driver = await new Builder().forBrowser('firefox').build();
try {
// Navigate to Url
await driver.get('https://www.example.com');
// Get all the elements available with tag 'p'
let elements = await driver.findElements(By.css('p'));
for(let e of elements) {
console.log(await e.getText());
}
}
finally {
await driver.quit();
}
})();
import org.openqa.selenium.By
import org.openqa.selenium.firefox.FirefoxDriver
fun main() {
val driver = FirefoxDriver()
try {
driver.get("https://example.com")
// Get all the elements available with tag name 'p'
val elements = driver.findElements(By.tagName("p"))
for (element in elements) {
println("Paragraph text:" + element.text)
}
} finally {
driver.quit()
}
}
It is used to find the list of matching child WebElements within the context of parent element. To achieve this, the parent WebElement is chained with ‘findElements’ to access child elements
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.List;
public class findElementsFromElement {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
try {
driver.get("https://example.com");
// Get element with tag name 'div'
WebElement element = driver.findElement(By.tagName("div"));
// Get all the elements available with tag name 'p'
List<WebElement> elements = element.findElements(By.tagName("p"));
for (WebElement e : elements) {
System.out.println(e.getText());
}
} finally {
driver.quit();
}
}
}
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.get("https://www.example.com")
# Get element with tag name 'div'
element = driver.find_element(By.TAG_NAME, 'div')
# Get all the elements available with tag name 'p'
elements = element.find_elements(By.TAG_NAME, 'p')
for e in elements:
print(e.text)
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using System.Collections.Generic;
namespace FindElementsFromElement {
class FindElementsFromElement {
public static void Main(string[] args) {
IWebDriver driver = new ChromeDriver();
try {
driver.Navigate().GoToUrl("https://example.com");
// Get element with tag name 'div'
IWebElement element = driver.FindElement(By.TagName("div"));
// Get all the elements available with tag name 'p'
IList < IWebElement > elements = element.FindElements(By.TagName("p"));
foreach(IWebElement e in elements) {
System.Console.WriteLine(e.Text);
}
} finally {
driver.Quit();
}
}
}
}
require 'selenium-webdriver'
driver = Selenium::WebDriver.for :chrome
begin
# Navigate to URL
driver.get 'https://www.example.com'
# Get element with tag name 'div'
element = driver.find_element(:tag_name,'div')
# Get all the elements available with tag name 'p'
elements = element.find_elements(:tag_name,'p')
elements.each { |e|
puts e.text
}
ensure
driver.quit
end
const {Builder, By} = require('selenium-webdriver');
(async function example() {
let driver = new Builder()
.forBrowser('chrome')
.build();
await driver.get('https://www.example.com');
// Get element with tag name 'div'
let element = driver.findElement(By.css("div"));
// Get all the elements available with tag name 'p'
let elements = await element.findElements(By.css("p"));
for(let e of elements) {
console.log(await e.getText());
}
})();
import org.openqa.selenium.By
import org.openqa.selenium.chrome.ChromeDriver
fun main() {
val driver = ChromeDriver()
try {
driver.get("https://example.com")
// Get element with tag name 'div'
val element = driver.findElement(By.tagName("div"))
// Get all the elements available with tag name 'p'
val elements = element.findElements(By.tagName("p"))
for (e in elements) {
println(e.text)
}
} finally {
driver.quit()
}
}
It is used to track (or) find DOM element which has the focus in the current browsing context.
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
public class activeElementTest {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
try {
driver.get("http://www.google.com");
driver.findElement(By.cssSelector("[name='q']")).sendKeys("webElement");
// Get attribute of current active element
String attr = driver.switchTo().activeElement().getAttribute("title");
System.out.println(attr);
} finally {
driver.quit();
}
}
}
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.get("https://www.google.com")
driver.find_element(By.CSS_SELECTOR, '[name="q"]').send_keys("webElement")
# Get attribute of current active element
attr = driver.switch_to.active_element.get_attribute("title")
print(attr)
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
namespace ActiveElement {
class ActiveElement {
public static void Main(string[] args) {
IWebDriver driver = new ChromeDriver();
try {
// Navigate to Url
driver.Navigate().GoToUrl("https://www.google.com");
driver.FindElement(By.CssSelector("[name='q']")).SendKeys("webElement");
// Get attribute of current active element
string attr = driver.SwitchTo().ActiveElement().GetAttribute("title");
System.Console.WriteLine(attr);
} finally {
driver.Quit();
}
}
}
}
require 'selenium-webdriver'
driver = Selenium::WebDriver.for :chrome
begin
driver.get 'https://www.google.com'
driver.find_element(css: '[name="q"]').send_keys('webElement')
# Get attribute of current active element
attr = driver.switch_to.active_element.attribute('title')
puts attr
ensure
driver.quit
end
const {Builder, By} = require('selenium-webdriver');
(async function example() {
let driver = await new Builder().forBrowser('chrome').build();
await driver.get('https://www.google.com');
await driver.findElement(By.css('[name="q"]')).sendKeys("webElement");
// Get attribute of current active element
let attr = await driver.switchTo().activeElement().getAttribute("title");
console.log(`${attr}`)
})();
import org.openqa.selenium.By
import org.openqa.selenium.chrome.ChromeDriver
fun main() {
val driver = ChromeDriver()
try {
driver.get("https://www.google.com")
driver.findElement(By.cssSelector("[name='q']")).sendKeys("webElement")
// Get attribute of current active element
val attr = driver.switchTo().activeElement().getAttribute("title")
print(attr)
} finally {
driver.quit()
}
}
仅有五种基本命令可用于元素的操作:
这些方法的设计目的是尽量模拟用户体验, 所以, 与 Actions接口 不同, 在指定制定操作之前, 会尝试执行两件事.
元素点击命令 执行在 元素中央. 如果元素中央由于某些原因被 遮挡 , Selenium将返回一个 元素点击中断 错误.
元素发送键位命令
将录入提供的键位到 可编辑的 元素.
通常, 这意味着元素是具有 文本
类型的表单的输入元素或具有 内容可编辑
属性的元素.
如果不可编辑, 则返回
无效元素状态 错误.
以下 是WebDriver支持的按键列表.
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class HelloSelenium {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
try {
// Navigate to Url
driver.get("https://google.com");
// Enter text "q" and perform keyboard action "Enter"
driver.findElement(By.name("q")).sendKeys("q" + Keys.ENTER);
} finally {
driver.quit();
}
}
}
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox()
# Navigate to url
driver.get("http://www.google.com")
# Enter "webdriver" text and perform "ENTER" keyboard action
driver.find_element(By.NAME, "q").send_keys("webdriver" + Keys.ENTER)
using (var driver = new FirefoxDriver())
{
// Navigate to Url
driver.Navigate().GoToUrl("https://google.com");
// Enter "webdriver" text and perform "ENTER" keyboard action
driver.FindElement(By.Name("q")).SendKeys("webdriver" + Keys.Enter);
}
require 'selenium-webdriver'
driver = Selenium::WebDriver.for :firefox
begin
# Navigate to URL
driver.get 'https://google.com'
# Enter "webdriver" text and perform "ENTER" keyboard action
driver.find_element(name: 'q').send_keys 'webdriver', :return
ensure
driver.quit
end
const {Builder, By, Key} = require('selenium-webdriver');
(async function example() {
let driver = await new Builder().forBrowser('firefox').build();
try {
// Navigate to Url
await driver.get('https://www.google.com');
// Enter text "webdriver" and perform keyboard action "Enter"
await driver.findElement(By.name('q')).sendKeys('webdriver', Key.ENTER);
}
finally {
await driver.quit();
}
})();
import org.openqa.selenium.By
import org.openqa.selenium.Keys
import org.openqa.selenium.firefox.FirefoxDriver
fun main() {
val driver = FirefoxDriver()
try {
// Navigate to Url
driver.get("https://google.com")
// Enter text "q" and perform keyboard action "Enter"
driver.findElement(By.name("q")).sendKeys("q" + Keys.ENTER)
} finally {
driver.quit()
}
}
元素清除命令
重置元素的内容.
这要求元素 可编辑,
且 可重置.
通常, 这意味着元素是具有 文本
类型的表单的输入元素或具有 内容可编辑
属性的元素.
如果不满足这些条件, 将返回
无效元素状态 错误.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class clear {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
try {
// Navigate to Url
driver.get("https://www.google.com");
// Store 'SearchInput' element
WebElement searchInput = driver.findElement(By.name("q"));
searchInput.sendKeys("selenium");
// Clears the entered text
searchInput.clear();
} finally {
driver.quit();
}
}
}
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
# Navigate to url
driver.get("http://www.google.com")
# Store 'SearchInput' element
SearchInput = driver.find_element(By.NAME, "q")
SearchInput.send_keys("selenium")
# Clears the entered text
SearchInput.clear()
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using System;
namespace SnipetProjectDelete
{
class Program
{
static void Main(string[] args)
{
IWebDriver driver = new ChromeDriver();
try
{
// Navigate to Url
driver.Navigate().GoToUrl(@"https://www.google.com");
// Store 'SearchInput' element
IWebElement searchInput = driver.FindElement(By.Name("q"));
searchInput.SendKeys("selenium");
// Clears the entered text
searchInput.Clear();
}
finally
{
driver.Quit();
}
}
}
}
require 'selenium-webdriver'
driver = Selenium::WebDriver.for :chrome
begin
# Navigate to URL
driver.get 'https://google.com'
# store 'search_input' element
search_input = driver.find_element(name: 'q')
search_input.send_keys('selenium')
# Clears the entered text
search_input.clear
ensure
driver.quit
end
await driver.get('https://www.selenium.dev/selenium/web/inputs.html');
let inputField = await driver.findElement(By.name('no_type'));
await inputField.clear();
import org.openqa.selenium.By
import org.openqa.selenium.chrome.ChromeDriver
fun main() {
val driver = ChromeDriver()
try {
// Navigate to Url
driver.get("https://www.google.com")
// Store 'searchInput' element
val searchInput = driver.findElement(By.name("q"))
searchInput.sendKeys("selenium")
// Clears the entered text
searchInput.clear()
} finally {
driver.quit()
}
}
在Selenium 4中, 不再通过单独的端点以及脚本执行的方法来实现. 因此, 建议不要使用此方法, 而是单击相应的表单提交按钮.
定位器是在页面上标识元素的一种方法。它是传送给 查找元素 方法的参数。
查看 鼓励测试练习 寻找 定位器的小技巧, 包含在查找方法中,不同时间,不同原因下,单独声明的定位器的使用方法。
在 WebDriver 中有 8 种不同的内置元素定位策略:
定位器 Locator | 描述 |
---|---|
class name | 定位class属性与搜索值匹配的元素(不允许使用复合类名) |
css selector | 定位 CSS 选择器匹配的元素 |
id | 定位 id 属性与搜索值匹配的元素 |
name | 定位 name 属性与搜索值匹配的元素 |
link text | 定位link text可视文本与搜索值完全匹配的锚元素 |
partial link text | 定位link text可视文本部分与搜索值部分匹配的锚点元素。如果匹配多个元素,则只选择第一个元素。 |
tag name | 定位标签名称与搜索值匹配的元素 |
xpath | 定位与 XPath 表达式匹配的元素 |
Selenium 4 introduces Relative Locators (previously called as Friendly Locators). These locators are helpful when it is not easy to construct a locator for the desired element, but easy to describe spatially where the element is in relation to an element that does have an easily constructed locator.
Selenium uses the JavaScript function
getBoundingClientRect()
to determine the size and position of elements on the page, and can use this information to locate neighboring elements.
find the relative elements.
Relative locator methods can take as the argument for the point of origin, either a previously located element reference, or another locator. In these examples we’ll be using locators only, but you could swap the locator in the final method with an element object and it will work the same.
Let us consider the below example for understanding the relative locators.
If the email text field element is not easily identifiable for some reason, but the password text field element is, we can locate the text field element using the fact that it is an “input” element “above” the password element.
By emailLocator = RelativeLocator.with(By.tagName("input")).above(By.id("password"));
email_locator = locate_with(By.TAG_NAME, "input").above({By.ID: "password"})
var emailLocator = RelativeBy.WithLocator(By.TagName("input")).Above(By.Id("password"));
email_locator = {relative: {tag_name: 'input', above: {id: 'password'}}}
let emailLocator = locateWith(By.tagName('input')).above(By.id('password'));
val emailLocator = RelativeLocator.with(By.tagName("input")).above(By.id("password"))
If the password text field element is not easily identifiable for some reason, but the email text field element is, we can locate the text field element using the fact that it is an “input” element “below” the email element.
By passwordLocator = RelativeLocator.with(By.tagName("input")).below(By.id("email"));
password_locator = locate_with(By.TAG_NAME, "input").below({By.ID: "email"})
var passwordLocator = RelativeBy.WithLocator(By.TagName("input")).Below(By.Id("email"));
password_locator = {relative: {tag_name: 'input', below: {id: 'email'}}}
let passwordLocator = locateWith(By.tagName('input')).below(By.id('email'));
val passwordLocator = RelativeLocator.with(By.tagName("input")).below(By.id("email"))
If the cancel button is not easily identifiable for some reason, but the submit button element is, we can locate the cancel button element using the fact that it is a “button” element to the “left of” the submit element.
By cancelLocator = RelativeLocator.with(By.tagName("button")).toLeftOf(By.id("submit"));
cancel_locator = locate_with(By.TAG_NAME, "button").to_left_of({By.ID: "submit"})
var cancelLocator = RelativeBy.WithLocator(By.tagName("button")).LeftOf(By.Id("submit"));
cancel_locator = {relative: {tag_name: 'button', left: {id: 'submit'}}}
let cancelLocator = locateWith(By.tagName('button')).toLeftOf(By.id('submit'));
val cancelLocator = RelativeLocator.with(By.tagName("button")).toLeftOf(By.id("submit"))
If the submit button is not easily identifiable for some reason, but the cancel button element is, we can locate the submit button element using the fact that it is a “button” element “to the right of” the cancel element.
By submitLocator = RelativeLocator.with(By.tagName("button")).toRightOf(By.id("cancel"));
submit_locator = locate_with(By.TAG_NAME, "button").to_right_of({By.ID: "cancel"})
var submitLocator = RelativeBy.WithLocator(By.tagName("button")).RightOf(By.Id("cancel"));
submit_locator = {relative: {tag_name: 'button', right: {id: 'cancel'}}}
let submitLocator = locateWith(By.tagName('button')).toRightOf(By.id('cancel'));
val submitLocator = RelativeLocator.with(By.tagName("button")).toRightOf(By.id("cancel"))
If the relative positioning is not obvious, or it varies based on window size, you can use the near method to
identify an element that is at most 50px
away from the provided locator.
One great use case for this is to work with a form element that doesn’t have an easily constructed locator,
but its associated input label element does.
By emailLocator = RelativeLocator.with(By.tagName("input")).near(By.id("lbl-email"));
email_locator = locate_with(By.TAG_NAME, "input").near({By.ID: "lbl-email"})
var emailLocator = RelativeBy.WithLocator(By.tagName("input")).Near(By.Id("lbl-email"));
email_locator = {relative: {tag_name: 'input', near: {id: 'lbl-email'}}}
let emailLocator = locateWith(By.tagName('input')).near(By.id('lbl-email'));
val emailLocator = RelativeLocator.with(By.tagName("input")).near(By.id("lbl-email"));
You can also chain locators if needed. Sometimes the element is most easily identified as being both above/below one element and right/left of another.
By submitLocator = RelativeLocator.with(By.tagName("button")).below(By.id("email")).toRightOf(By.id("cancel"));
submit_locator = locate_with(By.TAG_NAME, "button").below