入門
Seleniumを初めて使用する場合は、すぐに習得するのに役立つリソースがいくつかあります。
Seleniumは市場で主要なブラウザの全てを WebDriver を使うことでサポートしています。
WebDriverとはAPI群とプロトコルです。これらはウェブブラウザの動作をコントロールするための言語中立なインターフェイスを定義しています。
それぞれのブラウザは特定のWebDriverの実装を持っており、これらは driver と呼ばれます。
driverはブラウザに委譲する責務を持つコンポーネントであり、Seleniumとブラウザ間の通信を処理します。
この分離は、ブラウザベンダーに自分たちのブラウザでの実装の責任を持たせるための意図的な努力のひとつです。
Seleniumは可能な場合これらのサードパーティ製のdriverを使いますが、それが現実的でない場合のためにプロジェクトでメンテナンスしているdriverも提供しています。
Seleniumフレームワークはこれら全ての要素をユーザ向けのインターフェイスを通して結びつけます。このインターフェイスは異なるブラウザバックエンドを透過的に使えるようにし、クロスブラウザ・クロスプラットフォームの自動化を可能にします。
Seleniumのセットアップは他の商用ツールと少し違います。自動化プロジェクトでSeleniumを使うためには、選択した言語の言語バインディングライブラリをインストールする必要があります。加えて、自動化でテストを実行したいブラウザのWebDriverバイナリも必要となります。
Seleniumのインストールは、次の3つのステップに分類することができます。
- 希望するプログラミング言語のSeleniumライブラリをインストールする。
- ブラウザを自動化するようにブラウザードライバを設定する。(例:Firefox用のGeckoDriver)
- (オプション)テストをスケールアップする場合は、Selenium Gridをセットアップして構成する。
ローコード/記録および再生ツールから始めたい場合は、Selenium IDE をチェックしてください。
セットアップが完了したら、ドキュメントのトップページに表示されているコードスニペットを実行できます。
次に、WebDriverの章に移動して、Seleniumを使用したブラウザーの自動化について詳しく学びます。
1 - Seleniumライブラリのインストール
お気に入りのプログラミング言語用にSeleniumライブラリを設定します。
最初にあなたの自動化プロジェクトにSeleniumのバインディングをインストールする必要があります。
インストールの方法は選択した言語によって異なります。
JavaへのSeleniumライブラリのインストールはMavenを使います。
プロジェクトのpom.xmlに selenium-java の依存関係を追加してください。
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.X</version>
</dependency>
selenium-java 依存関係は、Seleniumがサポートする全てのブラウザを自動化プロジェクトで実行できるようにします。
もし特定のブラウザだけでテストを実行したい場合は、そのブラウザの依存関係を pom.xml ファイルに追加することができます。
例えば、Firefoxのみでテストを実行するためには下記の依存関係を pom.xml ファイルに追加します。
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-firefox-driver</artifactId>
<version>4.X</version>
</dependency>
同じように、Chromeのみでテストを実行するためには下記の依存関係を追加します。
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-chrome-driver</artifactId>
<version>3.X</version>
</dependency>
PythonへのSeleniumライブラリのインストールはpipを使います。
また、PyPI source archive
(selenium-x.x.x.tar.gz)をダウンロードして、 setup.py でインストールすることもできます。
C#へのSeleniumライブラリのインストールはNuGetを使います。
# Using package manager
Install-Package Selenium.WebDriver
# or using .Net CLI
dotnet add package Selenium.WebDriver
Supported .NET Versions
Make sure to use the .NET SDK version compatible with relevant Selenium package.
Check the dependencies section to find out the supported .NET version.
At the time of this update, .NET 5.0 (Visual Studio 2019) is known to be supported, and .NET 6.0 is not supported.
You can download MSBuild Tools 2019 from here to install the needed components and dependencies such as .NET SDK and NuGet Package Manager.
Using Visual Studio Code (vscode) and C#
This is a quick guide to help you get started with vscode and C#, however, more research may be required.
Install the compatible .NET SDK as per the section above.
Also install the vscode extensions (Ctrl-Shift-X) for C# and NuGet.
Follow the instruction here
to create and run the “Hello World” console project using C#.
You may also create a NUnit starter project using the command line dotnet new NUnit
.
Make sure the file %appdata%\NuGet\nuget.config
is configured properly as some developers reported that it will be empty due to some issues.
If nuget.config
is empty, or not configured properly, then .NET builds will fail for Selenium Projects.
Add the following section to the file nuget.config
if it is empty:
<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>
...
For more info about nuget.config
click here.
You may have to customize nuget.config
to meet you needs.
Now, go back to vscode, press Ctrl-Shift-P, and type “NuGet Add Package”, and enter the required Selenium packages such as Selenium.WebDriver
.
Press Enter and select the version.
Now you can use the examples in the documentation related to C# with vscode.
RubyへのSeleniumライブラリのインストールはgemを使います。
gem install selenium-webdriver
JavaScriptへのSeleniumライブラリのインストールはnpmを使います。
npm install selenium-webdriver
Kotlinのネイティブ言語バインディングが欠落しているため、Javaバインディングを使用する必要があります。
例えば、 maven
Java を使用します。
Next Step
Install the browser drivers
2 - ブラウザーのドライバーをインストールする
自動化するブラウザを設定する。
Seleniumは、WebDriverを介して、Chrome/Chromium、Firefox、Internet Explorer、Edge、Opera、Safari
などの市場にあるすべての主要なブラウザーをサポートします。
可能な場合、WebDriverは、ブラウザーに組み込まれている自動化のサポートを使用してブラウザーを動かします。
Internet Explorerを除くすべてのドライバーの実装は、ブラウザーベンダー自身によって提供されているため、
標準のSeleniumディストリビューションには含まれていません。
この章では、さまざまなブラウザを使い始めるための基本的な要件について説明します。
Read about more advanced options for starting a driver
in our driver configuration documentation.
クイックリファレンス
Note: The Opera driver does not support w3c syntax, so we recommend using chromedriver to work with Opera.
See the code example for opening an Opera browser
ドライバーを使用する3つの方法
1. ドライバー管理ソフトウェア
ほとんどのマシンはブラウザを自動的に更新しますが、ドライバは更新しません。
ブラウザに適切なドライバを確実に入手するために、多くのサードパーティライブラリが役立ちます。
// Use WebDriverManager: https://github.com/bonigarcia/webdrivermanager
// Import WebDriver Manager:
import io.github.bonigarcia.wdm.WebDriverManager;
// Call setup() method for the browser driver you want:
WebDriverManager.chromedriver().setup();
// Initialize your driver as you normally would:
ChromeDriver driver = new ChromeDriver();
# Use Webdriver Manager for Python: https://github.com/SergeyPirogov/webdriver_manager
# Import code:
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service
# Use the `install()` method to set `executabe_path` in a new `Service` instance:
service = Service(executable_path=ChromeDriverManager().install())
# Pass in the `Service` instance with the `service` keyword:
driver = webdriver.Chrome(service=service)
// Use WebDriver Manager Package: https://github.com/rosolko/WebDriverManager.Net
// Import the dependencies:
using WebDriverManager;
using WebDriverManager.DriverConfigs.Impl;
// Use the `SetUpDriver()` which requires a config class:
new DriverManager().SetUpDriver(new ChromeConfig());
// Initialize your driver as you normally would:
var driver = new ChromeDriver()
# Use webdrivers gem: https://github.com/titusfortner/webdrivers
# Add gem to Gemfile:
gem 'webdrivers', '~> 5.0'
# Require webdrivers in your project:
require 'webdrivers'
# Initialize driver as you normally would:
driver = Selenium::WebDriver.for :chrome
// There is not a recommended driver manager for JavaScript at this time
// Use WebDriverManager: https://github.com/bonigarcia/webdrivermanager
// Import the library
import io.github.bonigarcia.wdm.WebDriverManager
// Call the setup method before initializing the driver as you normally would:
fun chrome(): WebDriver {
WebDriverManager.chromedriver().setup()
return ChromeDriver()
}
2. PATH
環境変数
このオプションでは、最初に手動でドライバーをダウンロードする必要があります
(リンクについてはクイックリファレンスを参照してください)。
これは、コードを更新せずにドライバーの場所を変更するための柔軟なオプションであり、各マシンがドライバーを同じ場所に配置する必要なく、複数のマシンで機能します。
PATH
にすでにリストされているディレクトリにドライバを配置するか、ディレクトリに配置して PATH
に追加することができます。
- すでに
PATH
にあるディレクトリを確認するには、コマンドプロンプト/ターミナルを開いて次のように入力します。
* ドライバを配置するディレクトリがまだPATHにない場合は、次のディレクトリを追加する必要があります。
export PATH=$PATH:/opt/WebDriver/bin >> ~/.profile
setx PATH "%PATH%;C:\WebDriver\bin"
* ドライバを起動することで、正しく追加されているかどうかをテストできます。
- If your
PATH
is configured correctly, 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. ハードコードされた場所
上記のオプション2と同様に、ドライバーを手動でダウンロードする必要があります。
(リンクについては クイックリファレンス を参照してください)。
コードそのものに場所を指定することには、システム上の環境変数を把握する必要がないという利点がありますが、
コードの柔軟性が大幅に低下するという欠点があります。
System.setProperty("webdriver.chrome.driver","/opt/WebDriver/bin/chromedriver");
ChromeDriver driver = new ChromeDriver();
from selenium.webdriver.chrome.service import Service
from selenium import webdriver
service = Service(executable_path="/opt/WebDriver/bin/chromedriver")
driver = webdriver.Chrome(service=service)
var driver = new ChromeDriver(@"C:\WebDriver\bin");
service = Selenium::WebDriver::Service.chrome(path: '/opt/WebDriver/bin/chromedriver')
driver = Selenium::WebDriver.for :chrome, service: service
const {Builder} = require('selenium-webdriver');
const chrome = require('selenium-webdriver/chrome');
const service = new chrome.ServiceBuilder('/opt/WebDriver/bin/chromedriver');
const driver = new Builder().forBrowser('chrome').setChromeService(service).build();
// Please raise a PR to add code sample
ブラウザの起動
Chromium/Chrome
デフォルトでは、Selenium4はChromev75以降と互換性があります。
Chromeのバージョンとchromedriverのバージョンはメジャーバージョンと一致する必要があることに注意してください。
該当するダウンロードリンクについては、クイックリファレンスを参照してください。
Chromeの起動方法の例は、前章、つまり詳しく説明したドライバーを使用する3つの方法に記載されています。
System.setProperty("webdriver.chrome.driver","/path/to/chromedriver");
ChromeDriver driver = new ChromeDriver();
import org.openqa.selenium.chrome.ChromeDriver
fun main(args: Array<String>) {
System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver")
val driver = ChromeDriver()
}
Edge
Microsoft Edgeは、サポートされている最も古いバージョンのv79を使用してChromiumで実装されています。
Chromeと同様に、Edgeのバージョンとedgedriverのバージョンはメジャーバージョンと一致する必要があります。
該当するダウンロードリンクについては、クイックリファレンスを参照してください。
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.edge.EdgeDriver;
WebDriver driver = new EdgeDriver();
from selenium.webdriver import Edge
driver = Edge()
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
IWebDriver driver = new EdgeDriver();
require "selenium-webdriver"
driver = Selenium::WebDriver.for :edge
const {Builder} = require('selenium-webdriver');
var driver = new Builder().forBrowser('edge').build();
import org.openqa.selenium.WebDriver
import org.openqa.selenium.Edge.EdgeDriver
val driver: WebDriver = EdgeDriver()
Firefox
Selenium4にはFirefox78以降が必要です。
常に最新バージョンのgeckodriverを使用することをお勧めします。
該当するダウンロードリンクについては、クイックリファレンスを参照してください。
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
WebDriver driver = new FirefoxDriver();
from selenium.webdriver import Firefox
driver = Firefox()
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
IWebDriver driver = new FirefoxDriver();
require "selenium-webdriver"
driver = Selenium::WebDriver.for :firefox
const {Builder} = require('selenium-webdriver');
var driver = new Builder().forBrowser('firefox').build();
import org.openqa.selenium.WebDriver
import org.openqa.selenium.Firefox.FirefoxDriver
val driver: WebDriver = FirefoxDriver()
Internet Explorer
Seleniumプロジェクトは、 Microsoftがカレントバージョンとみなすもの
と同じリリースをサポートすることを目的としています。
古いリリースは機能する可能性がありますが、サポートされません。
Internet Explorer 11は、2022年6月15日にWindows 10を含む特定のオペレーティングシステムのサポートを終了することに注意してください。Edgeには、引き続きサポートされるIE互換モードがあります。
IEドライバーは、Seleniumプロジェクトによって直接維持される唯一のドライバーです。
Internet Explorerの32ビットバージョンと64ビットバージョンの両方のバイナリを使用できますが、
64ビットドライバーにはいくつかの制限があります。
そのため、32ビットドライバを使用することをお勧めします。
Internet Explorerの設定はログインしたユーザーのアカウントに対して保存されるため、追加の設定が必要になることに注意してください。
Internet Explorerの使用に関する追加情報は、Selenium wikiにあり、
該当するダウンロードリンクのクイックリファレンスを参照してください。
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
WebDriver driver = new InternetExplorerDriver();
from selenium.webdriver import Ie
driver = Ie()
using OpenQA.Selenium;
using OpenQA.Selenium.IE;
IWebDriver driver = new InternetExplorerDriver();
require "selenium-webdriver"
driver = Selenium::WebDriver.for :ie
const {Builder} = require('selenium-webdriver');
var driver = new Builder().forBrowser('internet explorer').build();
import org.openqa.selenium.WebDriver
import org.openqa.selenium.ie.InternetExplorerDriver
val driver: WebDriver = InternetExplorerDriver()
Opera
Operaの現在のリリースはChromiumエンジン上に構築されており、
WebDriverはクローズドソースの Opera Chromium Driver を介してサポートされるようになりました。
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.opera.OperaDriver;
WebDriver driver = new OperaDriver();
from selenium.webdriver import Opera
driver = Opera()
using OpenQA.Selenium;
using OpenQA.Selenium.Opera;
IWebDriver driver = new OperaDriver();
# Not currently implemented
const {Builder} = require("selenium-webdriver");
var driver = new Builder().forBrowser('opera').build();
import org.openqa.selenium.WebDriver
import org.openqa.selenium.opera.OperaDriver
val driver: WebDriver = OperaDriver()
Safari
ChromiumおよびFirefoxドライバーとは異なり、safaridriverはオペレーティングシステムとともにインストールされます。
Safariで自動化を有効にするには、ターミナルから次のコマンドを実行します。
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.safari.SafariDriver;
WebDriver driver = new SafariDriver();
from selenium.webdriver import Safari
driver = Safari()
using OpenQA.Selenium;
using OpenQA.Selenium.Safari;
IWebDriver driver = new SafariDriver();
require "selenium-webdriver"
driver = Selenium::WebDriver.for :safari
const {Builder} = require('selenium-webdriver');
var driver = new Builder().forBrowser('safari').build();
import org.openqa.selenium.WebDriver
import org.openqa.selenium.safari.SafariDriver
val driver: WebDriver = SafariDriver()
iOSでSafariを自動化することを検討している人は、Appiumプロジェクトを検討する必要があります。
3 - Open and close a browser with Selenium
Code examples for starting and stopping a session with each browser.
Once you have a Selenium library installed,
and your desired browser driver,
you can start and stop a session with a browser.
Typically, browsers are started with specific options that describe
which capabilities the browser must support, and how the browser should
behave during the session. Some capabilities are
shared by all browsers, and
some will be specific to the browser being used.
This page will show examples of starting a browser with the default capabilities.
After learning how to start a session, check out the next session on how to
write your first Selenium script
Chrome
By default, Selenium 4 is compatible with Chrome v75 and greater. Note that the version of
the Chrome browser and the version of chromedriver must match the major version.
In addition to the shared capabilities,
there are specific Chrome capabilities
that can be used.
ChromeOptions options = new ChromeOptions();
driver = new ChromeDriver(options);
driver.quit();
options = ChromeOptions()
driver = webdriver.Chrome(options=options)
driver.quit()
var options = new ChromeOptions();
var driver = new ChromeDriver(options);
driver.Quit();
options = Selenium::WebDriver::Options.chrome
driver = Selenium::WebDriver.for :chrome, options: options
driver.quit
const {Builder} = require('selenium-webdriver');
const chrome = require('selenium-webdriver/chrome');
(async function openChromeTest() {
try {
let options = new chrome.Options();
let driver = await new Builder()
.setChromeOptions(options)
.forBrowser('chrome')
.build();
await driver.get('https://www.google.com');
await driver.quit();
} catch (error) {
console.log(error)
}
})();
val options = ChromeOptions()
val driver = ChromeDriver(options)
driver.quit()
Edge
Microsoft Edge is implemented with Chromium, with the earliest supported version of v79. Similar to Chrome,
the major version number of edgedriver must match the major version of the Edge browser.
EdgeOptions options = new EdgeOptions();
driver = new EdgeDriver(options);
driver.quit();
options = EdgeOptions()
driver = webdriver.Edge(options=options)
driver.quit()
var options = new EdgeOptions();
var driver = new EdgeDriver(options);
driver.Quit();
options = Selenium::WebDriver::Options.edge
driver = Selenium::WebDriver.for :edge, options: options
driver.quit
const {Builder} = require('selenium-webdriver');
const edge = require('selenium-webdriver/edge');
(async function openEdgeTest() {
try {
let options = new edge.Options();
let driver = await new Builder()
.setChromeOptions(options)
.forBrowser('edge')
.build();
await driver.get('https://www.google.com');
await driver.quit();
} catch (error) {
console.log(error)
}
})();
val options = EdgeOptions()
val driver = EdgeDriver(options)
driver.quit()
Firefox
Selenium 4 requires Firefox 78 or greater. It is recommended to always use the latest version of geckodriver.
FirefoxOptions options = new FirefoxOptions();
driver = new FirefoxDriver(options);
driver.quit();
options = FirefoxOptions()
driver = webdriver.Firefox(options=options)
driver.quit()
var options = new FirefoxOptions();
var driver = new FirefoxDriver(options);
driver.Quit();
options = Selenium::WebDriver::Options.firefox
driver = Selenium::WebDriver.for :firefox, options: options
driver.quit
const {Builder} = require('selenium-webdriver');
const firefox = require('selenium-webdriver/firefox');
(async function openFirefoxTest() {
try {
let options = new firefox.Options();
let driver = await new Builder()
.setChromeOptions(options)
.forBrowser('firefox')
.build();
await driver.get('https://www.google.com');
await driver.quit();
} catch (error) {
console.log(error)
}
})();
val options = FirefoxOptions()
val driver = FirefoxDriver(options)
driver.quit()
Internet Explorer
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
limitations
with the 64-bit driver. As such it is recommended to use the 32-bit driver.
Legacy
The Selenium project aims to support the same releases that
Microsoft considers current.
Older releases may work, but will not be supported. Note that Internet Explorer 11 will end support for certain
operating systems, including Windows 10 on June 15, 2022.
It should be noted that as Internet Explorer
preferences are saved against the logged-in user’s account, some additional setup is required.
Additional information about using Internet Explorer can be found
on the Selenium wiki
InternetExplorerOptions options = new InternetExplorerOptions();
driver = new InternetExplorerDriver(options);
driver.quit();
options = IEOptions()
driver = webdriver.Ie(options=options)
driver.quit()
var options = new InternetExplorerOptions();
var driver = new InternetExplorerDriver(options);
driver.Quit();
options = Selenium::WebDriver::Options.ie
driver = Selenium::WebDriver.for :ie, options: options
driver.quit
const { Builder } = require("selenium-webdriver");
const ie = require('selenium-webdriver/ie');
let options = new ie.Options();
let driver = await new Builder()
.forBrowser('internetExplorer')
.setIeOptions(options)
.build();
await driver.quit();
val options = InternetExplorerOptions()
val driver = InternetExplorerDriver(options)
driver.quit()
Compatibility Mode
Microsoft Edge can be used in IE compatibility mode using the IE Driver.
InternetExplorerOptions options = new InternetExplorerOptions();
options.attachToEdgeChrome();
options.withEdgeExecutablePath("/path/to/edge/browser");
driver = new InternetExplorerDriver(options);
driver.quit();
options = IEOptions()
options.attach_to_edge_chrome = True
options.edge_executable_path = "/path/to/edge/browser"
driver = webdriver.Ie(options=options)
driver.quit()
var options = new InternetExplorerOptions
{
AttachToEdgeChrome = true,
EdgeExecutablePath = "/path/to/edge/browser"
};
var driver = new InternetExplorerDriver(options);
driver.Quit();
options = Selenium::WebDriver::Options.ie
options.attach_to_edge_chrome = true
options.edge_executable_path = "/path/to/edge/browser"
driver = Selenium::WebDriver.for :ie, options: options
driver.quit
let options = new ie.Options();
options.setEdgeChromium(true);
options.setEdgePath("/path/to/edge/browser);
let driver = await new Builder()
.forBrowser('internet explorer')
.setIEOptions(options)
.build();
await driver.quit();
val options = InternetExplorerOptions()
options.attachToEdgeChrome()
options.withEdgeExecutablePath("/path/to/edge/browser")
val driver = InternetExplorerDriver(options)
driver.quit()
Opera
Since the opera driver does not set w3c as default value, but is based on Chromium, it is recommended
to drive Opera browser with the chromedriver. Like all Chromium implementations,
make sure that the browser version matches the driver version.
// Set webdriver.chrome.driver with Opera Driver
System.setProperty("webdriver.chrome.driver", "OPERA_DRIVER_PATH");
// Create ChromeOptions Instance
ChromeOptions chromeOptions = new ChromeOptions();
// Set W3C Dialect
chromeOptions.setExperimentalOption("w3c", true);
// Create ChromeDriver Instance
WebDriver driver = new ChromeDriver(chromeOptions);
// Open Target Website
driver.get("https://www.selenium.dev");
// Quit
driver.quit();
options = ChromeOptions()
options.binary_location = "path/to/opera/browser"
driver = webdriver.Chrome(options=options)
driver.quit()
var options = new ChromeOptions
{
BinaryLocation = "/path/to/opera/browser"
};
var driver = new ChromeDriver(options);
driver.Quit();
options = Selenium::WebDriver::Options.chrome
options.binary = '/path/to/opera/browser'
driver = Selenium::WebDriver.for :chrome, options: options
driver.quit
const { Builder } = require("selenium-webdriver");
const chrome = require('selenium-webdriver/chrome');
let options = new chrome.Options();
options.setChromeBinaryPath("/path/to/opera/browser");
let driver = await new Builder()
.forBrowser('chrome')
.setChromeOptions(options)
.build();
await driver.quit();
val options = ChromeOptions()
options.setBinary("/path/to/opera/browser")
val driver = ChromeDriver(options)
driver.quit()
Safari
Desktop
Unlike Chromium and Firefox drivers, the safaridriver is installed with the Operating System.
To enable automation on Safari, run the following command from the terminal:
SafariOptions options = new SafariOptions();
driver = new SafariDriver(options);
driver.quit();
driver = webdriver.Safari()
driver.quit()
var options = new SafariOptions();
var driver = new SafariDriver(options);
driver.Quit();
options = Selenium::WebDriver::Options.safari
driver = Selenium::WebDriver.for :safari, options: options
driver.quit
const { Builder } = require("selenium-webdriver");
const safari = require('selenium-webdriver/safari');
let options = new safari.Options();
let driver = await new Builder()
.forBrowser('safari')
.setSafariOptions(options)
.build();
await driver.quit();
val options = SafariOptions()
val driver = SafariDriver(options)
driver.quit()
Mobile
Those looking to automate Safari on iOS should look to the Appium project.
Next Step
Create your first Selenium script
4 - 最初のSeleniumスクリプトを書く
Seleniumスクリプトを作成するための段階的な説明
Seleniumをインストールし、
ドライバーをインストールすると、Seleniumコードを書く準備が整います。
Eight Basic Components
Seleniumが行うことはすべて、ブラウザコマンドを送信して、何かを実行したり、情報の要求を送信したりすることです。
Seleniumで行うことのほとんどは、次の基本的なコマンドの組み合わせです。
1. ドライバーインスタンスでセッションを開始します
For more details on starting a session read our documentation on opening and closing a browser
driver = new ChromeDriver();
driver = webdriver.Chrome()
var driver = new ChromeDriver();
driver = Selenium::WebDriver.for :chrome
let driver = await new Builder().forBrowser('chrome').build();
2. Take action on browser
In this example we are ブラウザがナビゲートするコマンドを送信します
driver.get("https://google.com");
driver.get("https://google.com")
driver.Navigate().GoToUrl("https://google.com");
driver.get('https://google.com')
await driver.get('https://www.google.com');
driver.get("https://google.com")
There are a bunch of types of information about the browser you
can request, including window handles, browser size / position, cookies, alerts, etc.
String title = driver.getTitle();
var title = driver.Title;
4. Establish Waiting Strategy
Synchronizing the code with the current state of the browser is one of the biggest challenges
with Selenium, and doing it well is an advanced topic.
Essentially you want to make sure that the element is on the page before you attempt to locate it
and the element is in an interactable state before you attempt to interact with it.
An implicit wait is rarely the best solution, but it’s the easiest to demonstrate here, so
we’ll use it as a placeholder.
Read more about Waiting strategies.
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: 1000})
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500))
5. 要素を検索するためのコマンドを送信します
The majority of commands in most Selenium sessions are element related, and you can’t interact
with one without first finding an element
WebElement searchBox = driver.findElement(By.name("q"));
WebElement searchButton = driver.findElement(By.name("btnK"));
search_box = driver.find_element(by=By.NAME, value="q")
search_button = driver.find_element(by=By.NAME, value="btnK")
var searchBox = driver.FindElement(By.Name("q"));
var searchButton = driver.FindElement(By.Name("btnK"));
search_box = driver.find_element(name: 'q')
search_button = driver.find_element(name: 'btnK')
let searchBox = await driver.findElement(By.name('q'));
let searchButton = await driver.findElement(By.name('btnK'));
var searchBox = driver.findElement(By.name("q"))
val searchButton = driver.findElement(By.name("btnK"))
6. 要素に対してアクションを実行する
There are only a handful of actions to take on an element,
but you will use them frequently.
searchBox.sendKeys("Selenium");
searchButton.click();
search_box.send_keys("Selenium")
search_button.click()
searchBox.SendKeys("Selenium");
searchButton.Click();
search_box.send_keys('Selenium')
search_button.click
await searchBox.sendKeys('Selenium');
await searchButton.click();
searchBox.sendKeys("Selenium")
searchButton.click()
7. 要素に関する情報をリクエストします
Elements store a lot of information that can be requested.
Notice that we need to relocate the search box because the DOM has changed since we first located it.
String value = searchBox.getAttribute("value");
value = search_box.get_attribute("value")
var value = searchBox.GetAttribute("value");
value = search_box.attribute('value')
let value = await searchBox.getAttribute("value");
val value = searchBox.getAttribute("value")
8. セッションを終了します
This ends the driver process, which by default closes the browser as well.
No more commands can be sent to this driver instance.
Putting everything together
これらの8つを組み合わせて、使う必要のあるライブラリを含む完全なスクリプトにしましょう。
package dev.selenium.getting_started;
import org.junit.jupiter.api.Assertions;
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;
public class FirstScriptTest {
public WebDriver driver;
@Test
public void eightComponents() {
driver = new ChromeDriver();
driver.get("https://google.com");
String title = driver.getTitle();
Assertions.assertEquals("Google", title);
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));
WebElement searchBox = driver.findElement(By.name("q"));
WebElement searchButton = driver.findElement(By.name("btnK"));
searchBox.sendKeys("Selenium");
searchButton.click();
searchBox = driver.findElement(By.name("q"));
String value = searchBox.getAttribute("value");
Assertions.assertEquals("Selenium", value);
driver.quit();
}
}
from selenium import webdriver
from selenium.webdriver.common.by import By
def test_eight_components():
driver = webdriver.Chrome()
driver.get("https://google.com")
title = driver.title
assert title == "Google"
driver.implicitly_wait(0.5)
search_box = driver.find_element(by=By.NAME, value="q")
search_button = driver.find_element(by=By.NAME, value="btnK")
search_box.send_keys("Selenium")
search_button.click()
search_box = driver.find_element(by=By.NAME, value="q")
value = search_box.get_attribute("value")
assert value == "Selenium"
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()
{
var driver = new ChromeDriver();
driver.Navigate().GoToUrl("https://google.com");
var title = driver.Title;
Assert.AreEqual("Google", title);
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(500);
var searchBox = driver.FindElement(By.Name("q"));
var searchButton = driver.FindElement(By.Name("btnK"));
searchBox.SendKeys("Selenium");
searchButton.Click();
searchBox = driver.FindElement(By.Name("q"));
var value = searchBox.GetAttribute("value");
Assert.AreEqual("Selenium", value);
driver.Quit();
}
}
}
# frozen_string_literal: true
RSpec.describe 'First Script' do
it 'uses eight components' do
driver = Selenium::WebDriver.for :chrome
driver.get('https://google.com')
title = driver.title
expect(title).to eq('Google')
driver.manage.timeouts.implicit_wait = 500
search_box = driver.find_element(name: 'q')
search_button = driver.find_element(name: 'btnK')
search_box.send_keys('Selenium')
search_button.click
search_box = driver.find_element(name: 'q')
value = search_box.attribute('value')
expect(value).to eq('Selenium')
driver.quit
end
end
const {Builder, By} = require('selenium-webdriver');
const assert = require('assert');
(async function firstScript() {
try {
let driver = await new Builder().forBrowser('chrome').build();
await driver.get('https://www.google.com');
await driver.getTitle();
await driver.manage().setTimeouts({implicit: 1000})
let searchBox = await driver.findElement(By.name('q'));
let searchButton = await driver.findElement(By.name('btnK'));
await searchBox.sendKeys('Selenium');
await searchButton.click();
let value = await searchBox.getAttribute("value");
assert.deepStrictEqual(value, "Selenium")
await driver.quit();
} catch (error) {
console.log(error)
}
})();
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
@Test
fun eightComponents() {
driver = ChromeDriver()
driver.get("https://google.com")
title = driver.title
assertEquals("Google", title)
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500))
var searchBox = driver.findElement(By.name("q"))
val searchButton = driver.findElement(By.name("btnK"))
searchBox.sendKeys("Selenium")
searchButton.click()
searchBox = driver.findElement(By.name("q"))
val value = searchBox.getAttribute("value")
assertEquals("Selenium", value)
driver.quit()
}
}
Next Steps
Take what you’ve learned and build out your Selenium code.
As you find more functionality that you need, read up on the rest of our
WebDriver documentation.
5 - Selenium4にアップグレードする方法
Selenium 4に興味がありますか? 最新リリースへのアップグレードに役立つこのガイドを確認してください。
公式にサポートされている言語(Ruby、JavaScript、C#、Python、およびJava)のいずれかを使用している場合、
Selenium4へのアップグレードは簡単なプロセスです。
いくつかの問題が発生する可能性がある場合があるかもしれません。このガイドは、それらを整理するのに役立ちます。
プロジェクトの依存関係をアップグレードする手順を実行し、バージョンのアップグレードによってもたらされる主な非推奨と変更を理解します。
これが、Selenium4にアップグレードするために実行する手順です。
- テストコードの準備
- 依存関係のアップグレード
- 潜在的なエラーと非推奨メッセージ
注:Selenium 3.xバージョンの開発中に、W3CWebDriver標準のサポートが実装されました。
この新しいプロトコルと従来のJSONワイヤープロトコルの両方がサポートされました。
バージョン3.11の前後で、SeleniumコードはレベルW3C1仕様に準拠するようになりました。
Selenium 3の最新バージョンのW3C準拠のコードは、Selenium4で期待どおりに機能します。
テストコードの準備
Selenium 4は、レガシープロトコルのサポートを削除し、内部でデフォルトでW3CWebDriver標準を使用します。
ほとんどの場合、この実装はエンドユーザーに影響を与えません。
主な例外は、Capabilities
と アクション
クラスです。
Capabilities
テスト機能がW3Cに準拠するように構成されていない場合、セッションが開始されない可能性があります。
W3CWebDriverの標準機能のリストは次のとおりです。
browserName
browserVersion
(version
に変更)platformName
(platform
に変更)acceptInsecureCerts
pageLoadStrategy
proxy
timeouts
unhandledPromptBehavior
標準Capabilitiesの最新リストは、 W3C WebDriver にあります。
上記のリストに含まれていないCapabilitiesには、ベンダープレフィックスを含める必要があります。
これは、ブラウザ固有のCapabilitiesとクラウドベンダー固有のCapabilitiesに適用されます。
たとえば、クラウドベンダーがテストに build
Capabilities と name
Capabilitiesを使用している場合は、
それらを cloud:options
ブロックでラップする必要があります(適切なプレフィックスについては、クラウドベンダーに確認してください)。
Before
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)
After
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で要素ユーティリティメソッドを検索する
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"));
依存関係のアップグレード
以下のサブセクションを確認してSelenium4をインストールし、プロジェクトの依存関係をアップグレードしてください。
Java
Seleniumをアップグレードするプロセスは、使用されているビルドツールによって異なります。
Javaで最も一般的なものであるMavenとGradleについて説明します。
必要なJavaの最小バージョンはまだ8です。
Maven
<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.0.0</version>
</dependency>
<!-- more dependencies ... -->
</dependencies>
変更を加えた後、pom.xml
ファイルと同じディレクトリで mvn clean compile
を実行できます。
Gradle
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.0.0'
}
test {
useJUnitPlatform()
}
変更を加えた後、 build.gradle
ファイルと同じディレクトリで ./gradlew cleanbuild
を実行できます。
すべてのJavaリリースを確認するには、 MVNRepository にアクセスしてください。
C#
C#でSelenium4の更新を取得する場所は NuGet です。
Selenium.WebDriver
パッケージの下で、最新バージョンに更新するための手順を入手できます。
Visual Studio内では、NuGetパッケージマネージャーを使用して次の操作を実行できます。
PM> Install-Package Selenium.WebDriver -Version 4.0.0
Python
Pythonを使用するための最も重要な変更は、最低限必要なバージョンです。
Selenium 4には、Python3.7以降が必要です。
詳細については、Python Package Indexを参照してください。
コマンドラインからアップグレードするには、次のコマンドを実行できます。
pip install selenium==4.0.0
Ruby
Selenium 4の更新の詳細は、RubyGemsのselenium-webdriverで確認できます。
最新バージョンをインストールするには、次のコマンドを実行できます。
gem install selenium-webdriver
Gemfileには下記のように追加します。
gem 'selenium-webdriver', '~> 4.0.0'
JavaScript
selenium-webdriverパッケージは、Nodeパッケージマネージャーのnpmjsにあります。
Selenium4はhereにあります。
これをインストールするには、次のいずれかを実行します。
npm install selenium-webdriver
または、package.jsonを更新して、 npm install
を実行します。
{
"name": "selenium-tests",
"version": "1.0.0",
"dependencies": {
"selenium-webdriver": "^4.0.0"
}
}
潜在的なエラーと非推奨メッセージ
これは、Selenium4にアップグレードした後に発生する可能性のある非推奨メッセージを克服するのに役立つ一連のコード例です。
Java
待機とタイムアウト
タイムアウトで受信するパラメーターは、期待値 (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
は、秒とミリ秒単位のタイムアウトに、 long
ではなくDuration
を期待するようになりました。
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は、もはや呼び出し元のオブジェクトを変更しなくなりました
以前は、別のCapabilitiesセットを別のセットにマージすることが可能であり、呼び出し元のオブジェクトを変更していました。
今は、ここで、マージ操作の結果を割り当てる必要があります。
MutableCapabilities capabilities = new MutableCapabilities();
capabilities.setCapability("platformVersion", "Windows 10");
FirefoxOptions options = new FirefoxOptions();
options.setHeadless(true);
options.merge(capabilities);
As a result, the options
object was getting modified.
MutableCapabilities capabilities = new MutableCapabilities();
capabilities.setCapability("platformVersion", "Windows 10");
FirefoxOptions options = new FirefoxOptions();
options.setHeadless(true);
options = options.merge(capabilities);
The result of the merge
call needs to be assigned to an object.
古いFirefox
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);
C#
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);
Python
execute_pathは非推奨になりました。Serviceオブジェクトを渡してください
Selenium 4では、非推奨の警告を防ぐために、Serviceオブジェクトからドライバーの executable_path
を設定する必要があります。
(または、PATHを設定せず、代わりに必要なドライバーがシステムPATH上にあることを確認してください。)
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 に投稿されました