Selenium ウェブドライバー Java プログラム例
⚡ スマートサマリー
Selenium webdriver Java プログラム例では、最初のエンドツーエンドの自動化スクリプトの作成手順を説明します。 Less本書では、環境設定、要素の特定、入力の送信、ナビゲーション、検証、待機、例外処理、および信頼性の高い WebDriver テストのためのベストプラクティスについて解説します。

Selenium Java 例:
使い方 Java class "myclass" that we created in the previous tutorial, let us try to create a WebDriver script that would:
ステップ1: フェッチ Mercury Tours' homepage
ステップ2: タイトルを確認する
ステップ3: 比較結果を出力する
ステップ4: プログラム全体を終了する前に閉じてください。
Selenium WebDriver サンプル Code
以下は、上記のシナリオで示されたロジックの実際の WebDriver コードです。
package newproject; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; //comment the above line and uncomment below line to use Chrome //import org.openqa.selenium.chrome.ChromeDriver; public class PG1 { public static void main(String[] args) { // declaration and instantiation of objects/variables System.setProperty("webdriver.gecko.">driver","C:\\geckodriver.exe"); WebDriver driver = new FirefoxDriver(); //comment the above 2 lines and uncomment below 2 lines to use Chrome //System.setProperty("webdriver.chrome.">driver","G:\\chromedriver.exe"); //WebDriver driver = new ChromeDriver(); String baseUrl = "https://demo.guru99.com/test/newtours/"; String expectedTitle = "Welcome: Mercury Tours"; String actualTitle = ""; // launch Fire fox and direct it to the Base URL driver.get(baseUrl); // get the actual value of the title actualTitle = driver.getTitle(); /* * compare the actual title of the page with the expected one and print * the result as "Passed" or "Failed" */ if (actualTitle.contentEquals(expectedTitle)){ System.out.println("Test Passed!"); } else { System.out.println("Test Failed"); } //close Fire fox driver.close(); } }
注: 開始中 Firefox 35 では、Web Driver を使用するには Mozilla によって作成された Gecko ドライバーを使用する必要があります。 Selenium 3.0、gecko、firefoxには互換性の問題があり、正しく設定するのは困難な作業になる可能性があります。コードが機能しない場合は、ダウングレードしてください。 Firefox バージョン 47 以下。あるいは、Chrome でスクリプトを実行することもできます。 Selenium Chromeではすぐに使えます。スクリプトをChromeで動作させるには、3行のコードを変更するだけで済みます。 Firefox
コードの説明
パッケージのインポート
開始するには、次の 2 つのパッケージをインポートする必要があります。
- org.openqa.selenium.*- contains the WebDriver class needed to instantiate a new browser loaded with a specific driver
- org.openqa.selenium.firefox です。Firefoxドライバ - contains the Firefoxインスタンス化に必要なドライバー クラス Firefox- WebDriver クラスによってインスタンス化されたブラウザ上での固有のドライバー
テストで、別のクラスへのアクセス、ブラウザーのスクリーンショットの取得、外部ファイルの操作など、より複雑なアクションが必要な場合は、間違いなくさらに多くのパッケージをインポートする必要があります。
オブジェクトと変数のインスタンス化
通常、これがドライバー オブジェクトのインスタンス化方法です。
WebDriver driver = new FirefoxDriver();
A Firefoxパラメーターのないドライバー クラスは、デフォルトを意味します Firefox プロフィールは、当社の Java プログラム。デフォルト Firefox プロファイルは起動に似ています Firefox セーフ モード (拡張機能はロードされていません)。
便宜上、ベースを保存しました URL そして、期待されるタイトルを変数として扱います。
ブラウザセッションの起動
WebDriver's 取得する() このメソッドは新しいブラウザセッションを開始し、それを URL パラメータとして指定するものです。
driver.get(baseUrl);
実際のページタイトルを取得する
WebDriver クラスには、 getTitle() 現在ロードされているページのページ タイトルを取得するために常に使用されるメソッド。
actualTitle = driver.getTitle();
期待値と実際の値を比較する
この部分のコードは、単に基本的な Java 実際のタイトルと予想されるタイトルを比較するための if-else 構造。
if (actualTitle.contentEquals(expectedTitle)){ System.out.println("Test Passed!"); } else { System.out.println("Test Failed"); }
ブラウザセッションの終了
「閉じる()" method is used to close the browser window.
driver.close();
プログラム全体の終了
このコマンドをすべてのブラウザウィンドウを閉じずに使用した場合、 Java ブラウザウィンドウを開いたままプログラムは終了します。
System.exit(0);
テストの実行
コードを実行するには XNUMX つの方法があります Eclipse IDE
- On Eclipse's menu bar, click 実行 > 実行。
- メディア掲載 Ctrlキー+ F11 コード全体を実行します。
すべてを正しく行った場合、 Eclipse would output "Test Passed!"
GUI要素の検索
Locating elements in WebDriver is done by using the "findElement(By.ロケータ())" method. The "locator" part of the code is same as any of the locators previously discussed in the Selenium IDE これらのチュートリアルの章。 実際、IDE を使用して GUI 要素を見つけ、正常に特定されたらコードを WebDriver にエクスポートすることをお勧めします。
ここにあります Selenium 要素をIDで特定するサンプルコード。Facebookをベースとして使用。 URL.
package newproject; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class PG2 { public static void main(String[] args) { System.setProperty("webdriver.gecko.">driver","C:\\geckodriver.exe"); WebDriver driver = new FirefoxDriver(); String baseUrl = "http://www.facebook.com"; String tagName = ""; driver.get(baseUrl); tagName = driver.findElement(By.id("email")).getTagName(); System.out.println(tagName); driver.close(); System.exit(0); } }
私たちは、使用しました getTagName() 方法tract the tag name of that particular element whose id is "email". When run, this code should be able to correctly identify the tag name "input" and will print it out on Eclipse's Console window.
要素の検索の概要
| 変動 | 詳細説明 | サンプル |
|---|---|---|
| By.className | finds elements based on the value of the "class" attribute | findElement(By.className("someClassName")) |
| By.cssSelector | finds elements based on the driver's underlying CSS Selector engine | findElement(By.cssSelector("input#email")) |
| IDで | locates elements by the value of their "id" attribute |
findElement(By.id("someId")) |
| By.linkText | 表示されている正確なテキストによってリンク要素を検索します |
findElement(By.linkText("REGISTRATION")) |
| 名前で | locates elements by the value of the "name" attribute |
findElement(By.name("someName")) |
| By.partialLinkText | 指定されたリンク テキストを含む要素を見つけます。 |
findElement(By.partialLinkText("REG")) |
| By.tagName | 要素をタグ名で検索します |
findElement(By.tagName("div")) |
| By.xpath | XPath を介して要素を検索します |
findElement(By.xpath("//html/body/div/table/tbody/tr/td[2]/table/ tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[2]/td[3]/ form/table/tbody/tr[5]")) |
findElement(By.cssSelector()) 使用上の注意
By.cssSelector() does not support the "contains" feature. Consider the Selenium IDE code below -
In Selenium 上記の IDE では、テスト全体が成功しました。ただし、 Selenium WebDriver script below, the same test generated an error because WebDriver does not support the "contains" keyword when used in the By.cssSelector() method.
一般的なコマンド
Web要素のインスタンス化
Instead of using the long "driver.findElement(By.locator())" syntax every time you will access a particular element, we can instantiate a WebElement object for it. The WebElement class is contained in the "org.openqa.selenium.*" package.
要素をクリックする
クリックはおそらく、Web 要素を操作する最も一般的な方法です。 の click() メソッドは、任意の要素のクリックをシミュレートするために使用されます。次の Selenium Java 例は、 click() クリックするために使用されました Mercury Tours' "Sign-In" button.
click() メソッドを使用する場合は、次の点に注意する必要があります。
- パラメータ/引数は必要ありません。
- このメソッドは、該当する場合、新しいページが読み込まれるまで自動的に待機します。
- クリックされる要素は表示されている必要があります (高さと幅がゼロであってはなりません)。
コマンドの取得
Get commands fetch various important information about the page/element. Here are some important "get" commands you must be familiar with.
| コマンド | 使用法 |
|---|---|
| 取得する()
サンプル使用法: |
|
| getTitle()
サンプル使用法: |
|
| getPageSource()
サンプル使用法: |
|
| getCurrentUrl()
サンプル使用法: |
|
| getText()
サンプル使用法: |
|
ナビゲートコマンド
これらのコマンドを使用すると、別の Web ページを更新したり、別の Web ページに移動したり、別の Web ページ間で切り替えたりすることができます。
| 案内する()
サンプル使用法: |
|
| ナビゲート().リフレッシュ()
サンプル使用法: |
|
| ナビゲート().back()
サンプル使用法: |
|
| ナビゲート().forward()
サンプル使用法: |
|
ブラウザを閉じて終了する Windows
| 閉じる()
サンプル使用法: |
|
| 終了する()
サンプル使用法: |
|
違いを明確に説明すると、 close() (NAIST) と quit(), 以下のコードを実行してみてください。 これは、ページの読み込み時に自動的にウィンドウをポップアップし、終了後に別のウィンドウを開く Web ページを使用します。
親ブラウザ ウィンドウのみが閉じられ、2 つのポップアップ ウィンドウは閉じられていないことに注意してください。
But if you use quit(), all windows will be closed - not just the parent one. Try running the code below and you will notice that the two pop-ups above will automatically be closed as well.
package newproject; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class PG3 { public static void main(String[] args) { System.setProperty("webdriver.gecko.">driver","C:\\geckodriver.exe"); WebDriver driver = new FirefoxDriver(); driver.get("http://www.popuptest.com/popuptest2.html"); driver.quit(); // using QUIT all windows will close } }
フレーム間の切り替え
フレーム内の GUI 要素にアクセスするには、フレーム内の要素にアクセスする前に、WebDriver がフレームまたはポップアップ ウィンドウにフォーカスするように指示する必要があります。 たとえば、Web ページを考えてみましょう。 https://demo.guru99.com/selenium/deprecated.html
This page has 3 frames whose "name" attributes are indicated above. We wish to access the "Deprecated" link encircled above in yellow. In order to do that, we must first instruct WebDriver to switch to the "classFrame" frame using the "switchTo().frame()" method. We will use the name attribute of the frame as the parameter for the "frame()" part.
package newproject; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class PG4 { public static void main(String[] args) { System.setProperty("webdriver.gecko.">driver","C:\\geckodriver.exe"); WebDriver driver = new FirefoxDriver(); driver.get("https://demo.guru99.com/selenium/deprecated.html"); driver.switchTo().frame("classFrame"); driver.findElement(By.linkText("Deprecated")).click(); driver.close(); } }
After executing this code, you will see that the "classFrame" frame is taken to the "Deprecated API" page, meaning that our code was successfully able to access the "Deprecated" link.
ポップアップの切り替え Windows
WebDriverでは、ポップアップウィンドウのようなアラートを表示できます。 Selenium IDE。アラート内の要素 (アラートに含まれるメッセージなど) にアクセスするには、 "switchTo().alert()" メソッドです。以下のコードでは、このメソッドを使用してアラートボックスにアクセスし、 "getText()" メソッドを使用して警告ボックスを自動的に閉じます "switchTo().alert().accept()" 方法。
まず、に向かいます https://output.jsbin.com/usidix/1 and manually click the "Go!" button there and see for yourself the message text.
見てみましょう Selenium これを行うコード例 -
package mypackage; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class myclass { public static void main(String[] args) { System.setProperty("webdriver.gecko.">driver","C:\\geckodriver.exe"); WebDriver driver = new FirefoxDriver(); String alertMessage = ""; driver.get("http://jsbin.com/usidix/1"); driver.findElement(By.cssSelector("input[value=\"Go!\"]")).click(); alertMessage = driver.switchTo().alert().getText(); driver.switchTo().alert().accept(); System.out.println(alertMessage); driver.quit(); } }
ソフトウェア設定ページで、下図のように Eclipse コンソールに表示されるアラート メッセージは次のとおりです。
待つ
待機にはXNUMX種類あります。
- Implicit wait - used to set the default waiting time throughout the program
- Explicit wait - used to set the waiting time for a particular instance only
暗黙的な待機
- 明示的待機よりもコーディングが簡単です。
- 通常、コードのインスタンス化部分で宣言されます。
- インポートするには追加のパッケージが XNUMX つだけ必要です。
暗黙的待機の使用を開始するには、このパッケージをコードにインポートする必要があります。
次に、コードのインスタンス化部分にこれを追加します。
明示的な待機
明示的な待機は、WebDriverWait クラスと ExpectedCondition クラスを使用して行われます。以下の Selenium WebDriver example, we shall wait up to 10 seconds for an element whose id is "username" to become visible before proceeding to the next command. Here are the steps.
ステップ1:
次の XNUMX つのパッケージをインポートします。
ステップ2:
Declare a WebDriverWait variable. In this example, we will use "myWaitVar" as the name of the variable.
ステップ3:
Use myWaitVar with ExpectedConditions on portions where you need the explicit wait to occur. In this case, we will use explicit wait on the "username" (Mercury Tours HomePage) input before we type the text "tutorial" onto it.
の賃貸条件
以下のメソッドは条件付きおよびルックで使用されますping operations --
- 有効になっています() コマンドを実行する前に、特定の要素が有効かどうかを確認したい場合に使用します。
- 表示される() コマンドを実行する前に、特定の要素が表示されているかどうかを確認する場合に使用します。
- isSelected() あることを確認したい場合に使用します。 チェックボックス、ラジオボタン、またはドロップダウンボックスのオプション が選択されます。 他の要素では機能しません。
ExpectedConditions の使用
The ExpectedConditions class offers a wider set of conditions that you can use in conjunction with WebDriverWait's until() method.
以下に、最も一般的な ExpectedConditions メソッドの一部を示します。
- アラートは存在します() - waits until an alert box is displayed.
- elementToBeClickable() - Waits until an element is visible and, at the same time, enabled. The sample Selenium Code below will wait until the element with id="username" to become visible and enabled first before assigning that element as a WebElement variable named "txtUserName".
- フレームToBeAvailableAndSwitchToIt() - Waits until the given frame is already available, and then automatically switches to it.
例外のキャッチ
isEnabled()、isDisplayed()、isSelected()を使用する場合、WebDriverは要素がすでにページに存在するものとみなします。そうでない場合は、 NoSuchElementException。 これを回避するには、プログラムが中断されないように try-catch ブロックを使用する必要があります。
WebElement txtbox_username = driver.findElement(By.id("username")); try{ if(txtbox_username.isEnabled()){ txtbox_username.sendKeys("tutorial"); } } catch(NoSuchElementException nsee){ System.out.println(nsee.toString()); }
If you use explicit waits, the type of exception that you should catch is the "TimeoutException".

.png)
.png)
.png)
.png)
.png)
.png)

.png)


.png)
.png)
.png)
.png)
.png)
.png)

.png)
.png)
.png)