トップページ > Selenium API(逆引き) > 【Ruby】script_timeout

【Ruby】script_timeout・・・javascript実行が終了するまでの待ち時間を設定する

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

「script_timeout」を実行することで、javascript実行が終了するまでの待ち時間を設定することが出来ます。

下記サンプルでは、指定したドライバに対して「script_timeout」を実行しています。「script_timeout」に数値(秒数)を代入することで指定した待ち時間の間、javascript実行が終了するまで待機します。 仮にjavascript実行時間が「script_timeout」に代入した待ち時間を超えた場合は、ScriptTimeOutErrorが発生してしまいます。

説明

◆メソッド
  ・script_timeout
◆使用形態
  ・driver.manage.timeouts.script_timeout = 10
◆備考
  ・待ち時間には秒数を指定
  ・非同期スクリプトの待ち時間を設定する
  ・設定した待ち時間を越えてjavascriptが動作していた場合ScriptTimeOutErrorが発生する
◆関連項目
  ・指定したドライバの要素が見つかるまでの待ち時間を設定する
  ・ページがロードされるまでの待ち時間を設定する

サンプル

require 'selenium-webdriver'
 
# Firefoxを起動
driver = Selenium::WebDriver.for(:firefox)
#Javascript実行が終了するまで最大5秒間待つように指定
driver.manage.timeouts.script_timeout = 5
#現在時刻を取得
startTime = Time.now
#指定時間待機する非同期スクリプト(ここでは3秒待機)
driver.execute_async_script('window.setTimeout(arguments[arguments.length - 1], 3000);')
#3秒後に再び時刻を取得
stopTime = Time.now
#差分の時間を表示する
print(stopTime - startTime)
※selenium version 4.1.0で動作確認をしています

実行結果

3.017024

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