トップページ > Selenium API(逆引き) > 条件を指定して待機について

条件を指定して待機について

【PR】業界トップクラスの「高単価報酬」「低マージン」を実現!レバテックフリーランス

説明

Seleniumでは、条件を指定することで、特定の条件下で処理を待機させることが出来ます。
具体的にはAlertが表示するまで処理を待機させたり、ボタンが非表示状態から表示状態にかわるまで待機させることも可能です。

以下、Javaを例として話を進めていきます。
条件を指定して待機するには、WebDriverWaitクラスとExpectedConditionsクラスを用いる必要があります。
	
まず、WebDriverWaitクラスのコンストラクタで、対象とするWebDriverと待機時間の最大値を指定し、インスタンスを作成します。
次に作成されたインスタンスに対してuntilメソッドを実行します。
untilメソッドは引数に条件を指定し、条件が「真」になるまで待機時間の最大値内で待機させるメソッドです。

次にuntilメソッドの引数となる、ExpectedConditionsクラスで具体的な条件を設定していきます。ExpectedConditionsクラスは静的クラスなので、「ExpectedConditions.xxx」の形でxxxのメソッドを実行します(xxxは条件となるメソッド)。


	①対象のWebDriverと待機時間(秒)の最大値を引数に渡し、WebDriverWaitクラスの
      インスタンスを生成する。
                //指定したdriverに対して最大で10秒間待機する
        WebDriverWait wait = new WebDriverWait(driver, 10);
	
	②wait.until(ExpectedConditions.xxx)の形で条件を指定していく。
           xxxの部分はExpectedConditionsクラスのメソッドを指定する。
           
              //Yahooを含むページタイトルを取得できるまで待機する(10秒超えたらException発生)
              boolean isTitle = wait.until(ExpectedConditions.titleContains("Yahoo"));

Fatal error: Uncaught Google_Service_Exception: Error calling GET https://www.googleapis.com/analytics/v3/data/ga?ids=ga%3A138132118&start-date=7daysAgo&end-date=yesterday&metrics=ga%3Apageviews&dimensions=ga%3ApageTitle%2C+ga%3ApagePath&sort=-ga%3Apageviews&max-results=1000: (404) <!DOCTYPE html> <html lang=en> <meta charset=utf-8> <meta name=viewport content="initial-scale=1, minimum-scale=1, width=device-width"> <title>Error 404 (Not Found)!!1</title> <style> *{margin:0;padding:0}html,code{font:15px/22px arial,sans-serif}html{background:#fff;color:#222;padding:15px}body{margin:7% auto 0;max-width:390px;min-height:180px;padding:30px 0 15px}* > body{background:url(//www.google.com/images/errors/robot.png) 100% 5px no-repeat;padding-right:205px}p{margin:11px 0 22px;overflow:hidden}ins{color:#777;text-decoration:none}a img{border:0}@media screen and (max-width:772px){body{background:none;margin-top:0;max-width:none;padding-right:0}}#logo{background:url(//www.google.com/images/branding/googlelogo/1x/googlelogo_c in /home/users/1/monda-muki/web/seleniumqref.com/google-api-php-client-1-master/src/Google/Http/REST.php on line 110