每个浏览器都有定制和特有的功能。
支持的浏览器列表
- 1: Chrome 特定功能
- 2: Edge 特定功能
- 3: Firefox specific functionality
- 4: IE specific functionality
- 5: Safari 特定功能
1 - Chrome 特定功能
默认情况下,Selenium 4与Chrome v75及更高版本兼容. 但是请注意Chrome浏览器的版本与chromedriver的主版本需要匹配.
Options
所有浏览器的通用功能请看这 Options page.
Chrome浏览器的特有功能可以在谷歌的页面找到: Capabilities & ChromeOptions
基于默认选项的Chrome浏览器会话看起来是这样:
ChromeOptions options = new ChromeOptions();
driver = new ChromeDriver(options);
options = webdriver.ChromeOptions()
driver = webdriver.Chrome(options=options)
var options = new ChromeOptions();
driver = new ChromeDriver(options);
options = Selenium::WebDriver::Options.chrome
@driver = Selenium::WebDriver.for :chrome, options: options
const Options = new Chrome.Options();
let driver = await env
.builder()
.setChromeOptions(Options)
.build();
下面是一些不同功能的常见示例:
参数
args
参数用于启动浏览器时要使用的命令行开关列表.
有两个很好的资源可以用于研究这些参数:
常用的参数包括 --start-maximized
, --headless=new
以及 --user-data-dir=...
向选项添加参数:
options.addArguments("--start-maximized");
options.add_argument("--start-maximized")
options.AddArgument("--start-maximized");
options.args << '--start-maximized'
let driver = await env
.builder()
.setChromeOptions(options.addArguments('--headless=new'))
.build();
从指定位置启动浏览器
binary
参数接收一个使用浏览器的备用路径,通过这个参数你可以使用chromedriver 去驱动各种基于Chromium 内核的浏览器.
添加一个浏览器地址到选项中:
options.setBinary(getChromeLocation());
options.binary_location = chrome_bin
options.BinaryLocation = GetChromeLocation();
options.binary = chrome_location
let driver = await env
.builder()
.setChromeOptions(options.setChromeBinaryPath(`Path to chrome binary`))
.build();
添加扩展程序
extensions
参数接受crx文件. 至于解压的目录,
请使用 load-extension
参数代替,
正如 这篇文章 所示.
添加一个扩展程序到选项中:
options.addExtensions(extensionFilePath);
options.add_extension(extension_file_path)
options.AddExtension(extensionFilePath);
options.add_extension(extension_file_path)
const options = new Chrome.Options();
let driver = await env
.builder()
.setChromeOptions(options.addExtensions(['./test/resources/extensions/webextensions-selenium-example.crx']))
.build();
保持浏览器的打开状态
将 detach
参数设置为true将在驱动过程结束后保持浏览器的打开状态.
添加一个布尔值到选项中:
Note: This is already the default behavior in Java.
options.add_experimental_option("detach", True)
Note: This is already the default behavior in .NET.
options.detach = true
let driver = await env
.builder()
.setChromeOptions(options.detachDriver(true))
.build();
排除的参数
Chrome 添加了各种参数,如果你不希望添加某些参数,可以将其传入 excludeSwitches
.
一个常见的例子是重新打开弹出窗口阻止程序.
默认参数的完整列表可以参考
Chromium 源码
设置排除参数至选项中:
options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));
options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])
options.AddExcludedArgument("disable-popup-blocking");
options.exclude_switches << 'disable-popup-blocking'
let driver = await env
.builder()
.setChromeOptions(options.excludeSwitches('enable-automation'))
.build();
服务
创建默认 Service 对象的示例, 以及用于设置驱动程序位置和端口 可以参考 驱动服务 页面.
日志输出
获取驱动程序日志有助于调试问题. 使用 Service 类, 可以指明日志的路径. 除非用户将其定向到某个位置, 否则将忽略日志记录输出.
文件输出
更改日志记录输出以保存到特定文件:
ChromeDriverService service =
new ChromeDriverService.Builder().withLogFile(logLocation).build();
注意: Java 还允许通过系统属性设置文件输出:
属性键: ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY
属性值: 表示日志文件路径的字符串
service.LogPath = GetLogLocation();
命令行输出
更改日志记录输出以在控制台中显示为标准输出:
ChromeDriverService service =
new ChromeDriverService.Builder().withLogOutput(System.out).build();
注意: Java 还允许通过系统属性设置控制台输出;
属性键: ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY
属性值: DriverService.LOG_STDOUT
或 DriverService.LOG_STDERR
service = webdriver.ChromeService(log_output=subprocess.STDOUT)
$stdout
and $stderr
are both valid values
service.log = $stdout
日志级别
共有六种日志级别: ALL
, DEBUG
, INFO
, WARNING
, SEVERE
, 以及 OFF
.
注意 --verbose
等效于 --log-level=ALL
以及 --silent
等效于 --log-level=OFF
,
因此, 此示例只是通用地设置日志级别:
ChromeDriverService service =
new ChromeDriverService.Builder().withLogLevel(ChromiumDriverLogLevel.DEBUG).build();
注意: Java 还允许通过系统属性设置日志级别:
属性键: ChromeDriverService.CHROME_DRIVER_LOG_LEVEL_PROPERTY
属性值: ChromiumDriverLogLevel
枚举的字面值
service = webdriver.ChromeService(service_args=['--log-level=DEBUG'], log_output=subprocess.STDOUT)
日志文件功能
有 2 个功能仅在写入文件时可用:
- 追加日志
- 可读时间戳
要使用它们, 您还需要显式指定日志路径和日志级别. 日志输出将由驱动程序管理, 而不是由进程管理, 因此可能会看到细微的差异.
ChromeDriverService service =
new ChromeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();
注意: Java 还允许通过系统属性切换这些功能:
属性键: ChromeDriverService.CHROME_DRIVER_APPEND_LOG_PROPERTY
以及 ChromeDriverService.CHROME_DRIVER_READABLE_TIMESTAMP
属性值: "true"
或 "false"
service = webdriver.ChromeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)
service.args << '--append-log'
service.args << '--readable-timestamp'
禁用构建检查
Chromedriver 和 Chrome 浏览器版本应该匹配, 如果它们不匹配, 驱动程序将出错. 如果您停用构建检查功能, 则可以强制将驱动程序与任何版本的 Chrome 一起使用. 请注意, 这是一项不受支持的功能, 并且不会调查 bug.
ChromeDriverService service =
new ChromeDriverService.Builder().withBuildCheckDisabled(true).build();
注意: Java 还允许通过系统属性禁用构建检查:
属性键: ChromeDriverService.CHROME_DRIVER_DISABLE_BUILD_CHECK
属性值: "true"
或 "false"
service = webdriver.ChromeService(service_args=['--disable-build-check'], log_output=subprocess.STDOUT)
service.DisableBuildCheck = true;
特殊功能
Casting
你可以驱动 Chrome Cast 设备,包括共享选项卡
sinks = @driver.cast_sinks
unless sinks.empty?
device_name = sinks.first['name']
@driver.start_cast_tab_mirroring(device_name)
expect { @driver.stop_casting(device_name) }.not_to raise_exception
end
网络条件
您可以模拟各种网络条件.
以下示例适用于本地 webdrivers. 针对远程 webdrivers, 请参考 Remote WebDriver 页面.
@driver.network_conditions = {offline: false, latency: 100, throughput: 200}
日志
logs = @driver.logs.get(:browser)
权限
@driver.add_permission('camera', 'denied')
@driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
DevTools
详见 Chrome DevTools 部分以获取有关使用Chrome DevTools的更多信息
2 - Edge 特定功能
微软Edge是用Chromium实现的,最早支持版本是v79. 与Chrome类似, Edge驱动的主版本号必须与Edge浏览器的主要版本匹配.
在 Chrome 页面 上找到的所有capabilities和选项也适用于Edge.
选项
Capabilities common to all browsers are described on the Options page.
Capabilities unique to Chromium are documented at Google’s page for Capabilities & ChromeOptions
使用基本定义的选项启动 Edge 会话如下所示:
EdgeOptions options = new EdgeOptions();
driver = new EdgeDriver(options);
options = webdriver.EdgeOptions()
driver = webdriver.Edge(options=options)
var options = new EdgeOptions();
driver = new EdgeDriver(options);
options = Selenium::WebDriver::Options.edge
@driver = Selenium::WebDriver.for :edge, options: options
driver = await env.builder()
.setEdgeOptions(options)
.build();
});
Arguments
The args
parameter is for a list of command line switches to be used when starting the browser.
There are two excellent resources for investigating these arguments:
Commonly used args include --start-maximized
and --headless=new
and --user-data-dir=...
Add an argument to options:
options.addArguments("--start-maximized");
options.add_argument("--start-maximized")
options.AddArgument("--start-maximized");
options.args << '--start-maximized'
.setEdgeOptions(options.addArguments('--headless=new'))
Start browser in a specified location
The binary
parameter takes the path of an alternate location of browser to use. With this parameter you can
use chromedriver to drive various Chromium based browsers.
Add a browser location to options:
options.setBinary(getEdgeLocation());
options.binary_location = edge_bin
options.BinaryLocation = GetEdgeLocation();
options.binary = edge_location
Add extensions
The extensions
parameter accepts crx files. As for unpacked directories,
please use the load-extension
argument instead, as mentioned in
this post.
Add an extension to options:
options.addExtensions(extensionFilePath);
options.add_extension(extension_file_path)
options.AddExtension(extensionFilePath);
options.add_extension(extension_file_path)
.setEdgeOptions(options.addExtensions(['./test/resources/extensions/webextensions-selenium-example.crx']))
Keeping browser open
Setting the detach
parameter to true will keep the browser open after the process has ended,
so long as the quit command is not sent to the driver.
Note: This is already the default behavior in Java.
options.add_experimental_option("detach", True)
Note: This is already the default behavior in .NET.
options.detach = true
.setEdgeOptions(options.detachDriver(true))
Excluding arguments
MSEdgedriver has several default arguments it uses to start the browser.
If you do not want those arguments added, pass them into excludeSwitches
.
A common example is to turn the popup blocker back on. A full list of default arguments
can be parsed from the
Chromium Source Code
Set excluded arguments on options:
options.setExperimentalOption("excludeSwitches", List.of("disable-popup-blocking"));
options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])
options.AddExcludedArgument("disable-popup-blocking");
options.exclude_switches << 'disable-popup-blocking'
});
});
}, { browsers: [Browser.EDGE]});
Service
Examples for creating a default Service object, and for setting driver location and port can be found on the Driver Service page.
Log output
Getting driver logs can be helpful for debugging issues. The Service class lets you direct where the logs will go. Logging output is ignored unless the user directs it somewhere.
File output
To change the logging output to save to a specific file:
EdgeDriverService service = new EdgeDriverService.Builder().withLogFile(logLocation).build();
Note: Java also allows setting file output by System Property:
Property key: EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY
Property value: String representing path to log file
service = webdriver.EdgeService(log_output=log_path)
service.LogPath = GetLogLocation();
Console output
To change the logging output to display in the console as STDOUT:
EdgeDriverService service = new EdgeDriverService.Builder().withLogOutput(System.out).build();
Note: Java also allows setting console output by System Property;
Property key: EdgeDriverService.EDGE_DRIVER_LOG_PROPERTY
Property value: DriverService.LOG_STDOUT
or DriverService.LOG_STDERR
$stdout
and $stderr
are both valid values
service.log = $stdout
Log level
There are 6 available log levels: ALL
, DEBUG
, INFO
, WARNING
, SEVERE
, and OFF
.
Note that --verbose
is equivalent to --log-level=ALL
and --silent
is equivalent to --log-level=OFF
,
so this example is just setting the log level generically:
EdgeDriverService service =
new EdgeDriverService.Builder().withLoglevel(ChromiumDriverLogLevel.DEBUG).build();
Note: Java also allows setting log level by System Property:
Property key: EdgeDriverService.EDGE_DRIVER_LOG_LEVEL_PROPERTY
Property value: String representation of ChromiumDriverLogLevel
enum
service = webdriver.EdgeService(service_args=['--log-level=DEBUG'], log_output=log_path)
Log file features
There are 2 features that are only available when logging to a file:
- append log
- readable timestamps
To use them, you need to also explicitly specify the log path and log level. The log output will be managed by the driver, not the process, so minor differences may be seen.
EdgeDriverService service =
new EdgeDriverService.Builder().withAppendLog(true).withReadableTimestamp(true).build();
Note: Java also allows toggling these features by System Property:
Property keys: EdgeDriverService.EDGE_DRIVER_APPEND_LOG_PROPERTY
and EdgeDriverService.EDGE_DRIVER_READABLE_TIMESTAMP
Property value: "true"
or "false"
service = webdriver.EdgeService(service_args=['--append-log', '--readable-timestamp'], log_output=log_path)
service.args << '--append-log'
service.args << '--readable-timestamp'
Disabling build check
Edge browser and msedgedriver versions should match, and if they don’t the driver will error. If you disable the build check, you can force the driver to be used with any version of Edge. Note that this is an unsupported feature, and bugs will not be investigated.
EdgeDriverService service =
new EdgeDriverService.Builder().withBuildCheckDisabled(true).build();
Note: Java also allows disabling build checks by System Property:
Property key: EdgeDriverService.EDGE_DRIVER_DISABLE_BUILD_CHECK
Property value: "true"
or "false"
service = webdriver.EdgeService(service_args=['--disable-build-check'], log_output=log_path)
service.DisableBuildCheck = true;
Internet Explorer 兼容模式
微软Edge可以被"Internet Explorer兼容模式"驱动, 该模式使用Internet Explorer驱动类与微软Edge结合使用. 阅读 Internet Explorer 页面 了解更多详情.
Special Features
Some browsers have implemented additional features that are unique to them.
Casting
You can drive Chrome Cast devices with Edge, including sharing tabs
sinks = @driver.cast_sinks
unless sinks.empty?
device_name = sinks.first['name']
@driver.start_cast_tab_mirroring(device_name)
expect { @driver.stop_casting(device_name) }.not_to raise_exception
Network conditions
You can simulate various network conditions.
@driver.network_conditions = {offline: false, latency: 100, throughput: 200}
Logs
logs = @driver.logs.get(:browser)
Permissions
@driver.add_permission('camera', 'denied')
@driver.add_permissions('clipboard-read' => 'denied', 'clipboard-write' => 'prompt')
DevTools
See the [Chrome DevTools] section for more information about using DevTools in Edge
3 - Firefox specific functionality
Selenium 4 requires Firefox 78 or greater. It is recommended to always use the latest version of geckodriver.
Options
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 = webdriver.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:
Arguments
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:
options.addArguments("-headless");
options.add_argument("-headless")
options.AddArgument("-headless");
options.args << '-headless'
let driver = await env.builder()
.setFirefoxOptions(options.addArguments('--headless'))
.build();
Start browser in a specified location
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:
options.setBinary(getFirefoxLocation());
options.binary_location = firefox_bin
options.BinaryLocation = GetFirefoxLocation();
options.binary = firefox_location
Profiles
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)
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)
Service
Service settings common to all browsers are described on the Service page.
Log output
Getting driver logs can be helpful for debugging various issues. The Service class lets you direct where the logs will go. Logging output is ignored unless the user directs it somewhere.
File output
To change the logging output to save to a specific file:
FirefoxDriverService service =
new GeckoDriverService.Builder().withLogFile(logLocation).build();
Note: Java also allows setting file output by System Property:
Property key: GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY
Property value: String representing path to log file
service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])
Console output
To change the logging output to display in the console:
FirefoxDriverService service =
new GeckoDriverService.Builder().withLogOutput(System.out).build();
Note: Java also allows setting console output by System Property;
Property key: GeckoDriverService.GECKO_DRIVER_LOG_PROPERTY
Property value: DriverService.LOG_STDOUT
or DriverService.LOG_STDERR
service = webdriver.FirefoxService(log_output=subprocess.STDOUT)
Log level
There are 7 available log levels: fatal
, error
, warn
, info
, config
, debug
, trace
.
If logging is specified the level defaults to info
.
Note that -v
is equivalent to -log debug
and -vv
is equivalent to log trace
,
so this examples is just for setting the log level generically:
FirefoxDriverService service =
new GeckoDriverService.Builder().withLogLevel(FirefoxDriverLogLevel.DEBUG).build();
Note: Java also allows setting log level by System Property:
Property key: GeckoDriverService.GECKO_DRIVER_LOG_LEVEL_PROPERTY
Property value: String representation of FirefoxDriverLogLevel
enum
service = webdriver.FirefoxService(log_output=log_path, service_args=['--log', 'debug'])
Truncated Logs
The driver logs everything that gets sent to it, including string representations of large binaries, so Firefox truncates lines by default. To turn off truncation:
FirefoxDriverService service =
new GeckoDriverService.Builder().withTruncatedLogs(false).build();
Note: Java also allows setting log level by System Property:
Property key: GeckoDriverService.GECKO_DRIVER_LOG_NO_TRUNCATE
Property value: "true"
or "false"
service = webdriver.FirefoxService(service_args=['--log-no-truncate', '--log', 'debug'], log_output=log_path)
Profile Root
The default directory for profiles is the system temporary directory. If you do not have access to that directory, or want profiles to be created some place specific, you can change the profile root directory:
FirefoxDriverService service =
new GeckoDriverService.Builder().withProfileRoot(profileDirectory).build();
Note: Java also allows setting log level by System Property:
Property key: GeckoDriverService.GECKO_DRIVER_PROFILE_ROOT
Property value: String representing path to profile root directory
service = webdriver.FirefoxService(service_args=['--profile-root', temp_dir])
Special Features
Add-ons
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.
Installation
A signed xpi file you would get from Mozilla Addon page
driver.install_addon(addon_path_xpi)
driver.InstallAddOnFromFile(Path.GetFullPath(extensionFilePath));
driver.install_addon(extension_file_path)
const xpiPath = path.resolve('./test/resources/extensions/selenium-example.xpi')
let driver = await env.builder().build();
let id = await driver.installAddon(xpiPath);
Uninstallation
Uninstalling an addon requires knowing its id. The id can be obtained from the return value when installing the add-on.
String id = driver.installExtension(xpiPath);
driver.uninstall_addon(id)
driver.uninstall_addon(extension_id)
await driver.uninstallAddon(id);
Unsigned installation
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:
driver = startFirefoxDriver();
driver.install_addon(addon_path_dir, temporary=True)
driver.InstallAddOnFromDirectory(Path.GetFullPath(extensionDirPath), true);
const xpiPath = path.resolve('./test/resources/extensions/selenium-example')
let driver = await env.builder().build();
let id = await driver.installAddon(xpiPath, true);
Full page screenshots
The following examples are for local webdrivers. For remote webdrivers, please refer to the Remote WebDriver page.
screenshot = driver.save_full_page_screenshot(File.join(dir, 'screenshot.png'))
Context
The following examples are for local webdrivers. For remote webdrivers, please refer to the Remote WebDriver page.
driver.context = 'content'
4 - IE specific functionality
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.”
Special considerations
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
Options
Starting a Microsoft Edge browser in Internet Explorer Compatibility mode with basic defined options looks like this:
InternetExplorerOptions options = new InternetExplorerOptions();
options.attachToEdgeChrome();
options.withEdgeExecutablePath(getEdgeLocation());
driver = new InternetExplorerDriver(options);
options = webdriver.IeOptions()
options.attach_to_edge_chrome = True
options.edge_executable_path = edge_bin
driver = webdriver.Ie(options=options)
var options = new InternetExplorerOptions();
options.AttachToEdgeChrome = true;
options.EdgeExecutablePath = GetEdgeLocation();
_driver = new InternetExplorerDriver(options);
options = Selenium::WebDriver::IE::Options.new
options.attach_to_edge_chrome = true
options.edge_executable_path = edge_location
@driver = Selenium::WebDriver.for :ie, options: options
As of Internet Explorer Driver v4.5.0:
- If IE is not present on the system (default in Windows 11), you do not need to use the two parameters above. IE Driver will use Edge and will automatically locate it.
- If IE and Edge are both present on the system, you only need to set attaching to Edge, IE Driver will automatically locate Edge on your system.
So, if IE is not on the system, you only need:
InternetExplorerOptions options = new InternetExplorerOptions();
driver = new InternetExplorerDriver(options);
options = webdriver.IeOptions()
driver = webdriver.Ie(options=options)
var options = new InternetExplorerOptions();
_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();
<p><a href=/documentation/about/contributing/#moving-examples>
<span class="selenium-badge-code" data-bs-toggle="tooltip" data-bs-placement="right"
title="One or more of these examples need to be implemented in the examples directory; click for details in the contribution guide">Move Code</span></a></p>
val options = InternetExplorerOptions()
val driver = InternetExplorerDriver(options)
Here are a few common use cases with different capabilities:
fileUploadDialogTimeout
在某些环境中, 当打开文件上传对话框时, 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.file_upload_dialog_timeout = 2000
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)
ensureCleanSession
设置为 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.ensure_clean_session = true
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)
ignoreZoomSetting
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.ignore_zoom_level = true
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)
ignoreProtectedModeSettings
启动新的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.ignore_protected_mode_settings = true
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)
silent
设置为 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);
@options.silent = true
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()
}
}
IE 命令行选项
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";
}
}
}
@options.add_argument('-k')
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()
}
}
forceCreateProcessApi
强制使用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";
}
}
}
@options.force_create_process_api = true
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()
}
}
Service
Service settings common to all browsers are described on the Service page.
Log output
Getting driver logs can be helpful for debugging various issues. The Service class lets you direct where the logs will go. Logging output is ignored unless the user directs it somewhere.
File output
To change the logging output to save to a specific file:
.withLogFile(getLogLocation())
Note: Java also allows setting file output by System Property:
Property key: InternetExplorerDriverService.IE_DRIVER_LOGFILE_PROPERTY
Property value: String representing path to log file
service = webdriver.IeService(log_output=log_path, log_level='INFO')
Console output
To change the logging output to display in the console as STDOUT:
.withLogOutput(System.out)
Note: Java also allows setting console output by System Property;
Property key: InternetExplorerDriverService.IE_DRIVER_LOGFILE_PROPERTY
Property value: DriverService.LOG_STDOUT
or DriverService.LOG_STDERR
service = webdriver.IeService(log_output=subprocess.STDOUT)
Log Level
There are 6 available log levels: FATAL
, ERROR
, WARN
, INFO
, DEBUG
, and TRACE
If logging output is specified, the default level is FATAL
.withLogLevel(InternetExplorerDriverLogLevel.WARN)
Note: Java also allows setting log level by System Property:
Property key: InternetExplorerDriverService.IE_DRIVER_LOGLEVEL_PROPERTY
Property value: String representation of InternetExplorerDriverLogLevel.DEBUG.toString()
enum
service = webdriver.IeService(log_output=log_path, log_level='WARN')
Supporting Files Path
.withExtractPath(getTempDirectory())
service = webdriver.IeService(service_args=["–extract-path="+temp_dir])
5 - Safari 特定功能
与Chromium和Firefox驱动不同, safari驱动随操作系统安装. 要在 Safari 上启用自动化, 请从终端运行以下命令:
safaridriver --enable
选项
所有浏览器通用的Capabilities在选项页.
Safari独有的Capabilities可以在Apple的页面关于Safari的WebDriver 上找到
使用基本定义的选项启动 Safari 会话如下所示:
SafariOptions options = new SafariOptions();
driver = new SafariDriver(options);
options = webdriver.SafariOptions()
driver = webdriver.Safari(options=options)
var options = new SafariOptions();
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 项目.
服务
所有浏览器通用的服务设置在 服务页面.
日志
与其他浏览器不同,
Safari 浏览器不允许您选择日志的输出位置或更改级别.
一个可用选项是关闭或打开日志.
如果日志处于打开状态,
则可以在以下位置找到它们: ~/Library/Logs/com.apple.WebDriver/
.
.withLogging(true)
注意: Java也允许使用环境变量进行设置;
属性键: SafariDriverService.SAFARI_DRIVER_LOGGING
属性值: "true"
或 "false"
service = webdriver.SafariService(service_args=["--diagnose"])
Safari Technology Preview
Apple 提供了其浏览器的开发版本 — Safari Technology Preview
在代码中使用此版本:
Selenium::WebDriver::Safari.technology_preview!
local_driver = Selenium::WebDriver.for :safari