Selenium ウェブドライバー Java プログラム例

⚡ スマートサマリー

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

  • ⚙️ 環境設定: インストールを開始する Java, Eclipse または IntelliJ で設定します Selenium ライブラリを開き、お使いのブラウザのバージョンに合ったドライババイナリを選択してください。
  • 🧭 要素ロケーター: ID、名前、クラス、XPath、CSSセレクタ、およびリンクテキストを使用して、ブラウザやリリースに関わらず要素を安定的に識別します。
  • 特選割️ アクションと入力: WebDriverは、クリック、キー送信、送信、ドロップダウン選択、キーボードイベントをサポートしており、完全なユーザー操作を実現します。
  • ⏳ スマートな待ち時間: 不安定なテストを排除するために、Thread.sleep を ExpectedConditions によって駆動される暗黙的、明示的、かつ流暢な待機に置き換えます。
  • 🚨 例外処理: 自動化スイートの回復力を維持するために、NoSuchElementException、TimeoutException、およびStaleElementReferenceExceptionをキャッチしてください。
  • 🤖 AIテスト生成: AIアシスタントは、WebDriverの定型スクリプトを生成し、ロケーターを提案し、DOMが変更されたときにセレクターを自動的に修復します。

Selenium webdriver Java プログラム

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 つのパッケージをインポートする必要があります。

  1. org.openqa.selenium.*- contains the WebDriver class needed to instantiate a new browser loaded with a specific driver
  2. 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

  1. On Eclipse's menu bar, click 実行 > 実行。
  2. メディア掲載 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.

GUI要素の検索

要素の検索の概要

変動 詳細説明 サンプル
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 -

findElement(By.cssSelector()) 使用上の注意

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.

findElement(By.cssSelector()) 使用上の注意

一般的なコマンド

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要素のインスタンス化

要素をクリックする

クリックはおそらく、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.

コマンド 使用法
取得する()

サンプル使用法:

  • 新しいブラウザ ウィンドウが自動的に開き、括弧内に指定したページが取得されます。
  • の対応物です Selenium IDE's "open" command.
  • パラメータは次のとおりである必要があります String オブジェクト。
getTitle()

サンプル使用法:

  • パラメータは必要ありません
  • 現在のページのタイトルを取得します
  • 先頭と末尾の空白は削除されます
  • ページにタイトルがない場合は、NULL 文字列を返します。
getPageSource()

サンプル使用法:

  • パラメータは必要ありません
  • ページのソースコードを文字列値として返します。
getCurrentUrl()

サンプル使用法:

  • パラメータは必要ありません
  • 現在の文字列を表す文字列を取得します URL ブラウザが見ているもの
getText()

サンプル使用法:

  • 指定した要素の内部テキストを取得します。

ナビゲートコマンド

これらのコマンドを使用すると、別の Web ページを更新したり、別の Web ページに移動したり、別の Web ページ間で切り替えたりすることができます。

案内する()

サンプル使用法:

  • 新しいブラウザ ウィンドウが自動的に開き、括弧内に指定したページが取得されます。
  • とまったく同じことを行います get() 方法。
ナビゲート().リフレッシュ()

サンプル使用法:

  • パラメータは必要ありません。
  • 現在のページを更新します。
ナビゲート().back()

サンプル使用法:

  • パラメータは必要ありません
  • Takes you back by one page on the browser's history.
ナビゲート().forward()

サンプル使用法:

  • パラメータは必要ありません
  • Takes you forward by one page on the browser's history.

ブラウザを閉じて終了する Windows

閉じる()

サンプル使用法:

  • パラメータは必要ありません
  • WebDriver が現在制御しているブラウザ ウィンドウのみを閉じます。
終了する()

サンプル使用法:

  • パラメータは必要ありません
  • WebDriver が開いたすべてのウィンドウを閉じます。

ブラウザを閉じて終了する Windows

違いを明確に説明すると、 close() (NAIST) と quit(), 以下のコードを実行してみてください。 これは、ページの読み込み時に自動的にウィンドウをポップアップし、終了後に別のウィンドウを開く Web ページを使用します。

ブラウザを閉じて終了する Windows

親ブラウザ ウィンドウのみが閉じられ、2 つのポップアップ ウィンドウは閉じられていないことに注意してください。

ブラウザを閉じて終了する Windows

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.

ポップアップの切り替え Windows

見てみましょう 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 コンソールに表示されるアラート メッセージは次のとおりです。

ポップアップの切り替え Windows

待つ

待機にはXNUMX種類あります。

  1. Implicit wait - used to set the default waiting time throughout the program
  2. 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 --

  • 有効になっています() コマンドを実行する前に、特定の要素が有効かどうかを確認したい場合に使用します。

条件は有効です()

  • 表示される() コマンドを実行する前に、特定の要素が表示されているかどうかを確認する場合に使用します。

条件 isDisplayed()

  • isSelected() あることを確認したい場合に使用します。 チェックボックス、ラジオボタン、またはドロップダウンボックスのオプション が選択されます。 他の要素では機能しません。

条件 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.

ExpectedConditionsalertIsPresent() の使用

  • 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".

ExpectedConditions の使用

  • フレームToBeAvailableAndSwitchToIt() - Waits until the given frame is already available, and then automatically switches to it.

ExpectedConditions elementToBeClickable() の使用

例外のキャッチ

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".

例外のキャッチ

よくあるご質問

JDK、IDEなどをインストールします。 Eclipse または IntelliJ、 Selenium Java ライブラリと対応するブラウザドライバ。Maven などのビルド自動化ツールまたは Gradle 依存関係の管理を簡素化します。

AIはロケーターを自動修復し、ユーザーストーリーからテストケースを生成し、不安定なテストを特定します。 TestimMablやApplitoolsは、よりスマートなオーサリング、実行、ビジュアル検証のためにAIを組み込んでいます。

はい。GitHub Copilot、Cursor、そして JetBrains AI生成 Java Selenium 待機、アサーション、ページオブジェクトなどを含む、平易な言語で記述されたステップからスクリプトを作成します。これにより、新しいテストシナリオを作成する際の定型コードを大幅に削減できます。

findElement は、最初に見つかった一致する WebElement を返すか、NoSuchElementException をスローします。findElements は、一致するすべての WebElement のリストを返し、一致するものが見つからない場合は空のリストを返します。例外はスローされません。

Thread.sleep はページの状態に関係なく一定時間一時停止するため、高速な実行は遅くなり、低速な実行は失敗します。必要な時間だけ待機するには、ExpectedConditions を指定した WebDriverWait を使用してください。

Selenium ChromeDriver、GeckoDriverをサポート FirefoxEdgeDriver、SafariDriver、およびIEDriverServer。 Selenium バージョン4のマネージャーは、適切なドライバーを自動的にダウンロードします。

ChromeOptions を設定するか、 FirefoxSetAcceptInsecureCerts(true)を指定したOptionsオブジェクト。これにより、ブラウザは無効な証明書を無視し、WebDriverセッションを続行できるようになります。

WebDriverManagerは、インストールされているブラウザのバージョンに合わせて適切なブラウザドライババイナリを自動的にダウンロードして構成するため、手動でのドライバメンテナンスが不要になり、新規開発者のセットアップ時間を短縮できます。