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

【Python】implicitly_wait・・・指定したドライバの要素が見つかるまでの待ち時間を設定する

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

「implicitly_wait」を実行することで、指定したドライバの要素が見つかるまでの待ち時間を設定出来ます。

下記サンプルでは、GoogleTopページに遷移する前に、指定したドライバに対して「implicitly_wait」を実行しています。「implicitly_wait」の引数に数値(秒数)を指定することで、指定した待ち時間の間、要素が見つかるまで(ロードされるまで)待機します。また、「implicitly_wait」で指定されたdriverの要素全てに対して、見つかるまでの待ち時間を一律に指定していきます。 (下記サンプルに話を戻し)続いて「driver.find_element(By.ID, xxx)」で要素取得を試みていますが、指定したidである"abc"はGoogleTopページに実在しないidである為、要素を見つけることができません。しかし、画面遷移直後に要素がロードされていない時に待機するのと同じように、HTML上に実在しないidで要素取得を試みた場合でも、「implicitly_wait」で指定した待ち時間分待機します。

説明

◆メソッド
  ・implicitly_wait(time_to_wait)
◆使用形態
  ・driver.implicitly_wait(time_to_wait)
◆備考
  ・設定した待ち時間を越えても要素が見つからない場合は、Exceptionが発生
◆関連項目
  ・ページがロードされるまでの待ち時間を設定する
  ・javascript実行が終了するまでの待ち時間を設定する

サンプル

from selenium import webdriver
from selenium.webdriver.chrome import service
from selenium.webdriver.common.by import By

#ChromeDriverのパスを変数に設定
CHROMEDRIVER = "D:\driver\chromedriver.exe"
#ChromeDriverのstartとstopを制御するServiceオブジェクトを介してパスを渡す
chrome_service = service.Service(executable_path=CHROMEDRIVER)
#Chromeを起動
driver = webdriver.Chrome(service=chrome_service)
#要素がロードされるまでの待ち時間を10秒に設定
driver.implicitly_wait(10)
#指定したURLに遷移する
driver.get("https://google.co.jp/")
#存在しないIDを指定。10秒待った後にExceptionが発生するか確認
element = driver.find_element(By.ID, "abc")
※selenium version 4.1.3で動作確認をしています(ブラウザのUIや属性値などが変更された場合、実行結果が異なる可能性があります)

実行結果(10秒後にExceptionが発生)

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"id","selector":"abc"}
・
・
・

動画デモ

※字幕をONにすると解説のテロップが表示されます※


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: (403) User does not have sufficient permissions for this profile. in /home/users/1/monda-muki/web/seleniumqref.com/google-api-php-client-1-master/src/Google/Http/REST.php:110 Stack trace: #0 /home/users/1/monda-muki/web/seleniumqref.com/google-api-php-client-1-master/src/Google/Http/REST.php(62): Google_Http_REST::decodeHttpResponse(Object(Google_Http_Request), Object(Google_Client)) #1 /home/users/1/monda-muki/web/seleniumqref.com/google-api-php-client-1-master/src/Google/Task/Runner.php(174): Google_Http_REST::doExecute(Object(Google_Client), Object(Google_Http_Request)) #2 /home/users/1/monda-muki/web/seleniumqref.com/google-api-php-client-1-master/src/Google/Http/REST.php(46): Google_Task_Runner->run() #3 /home/users/1/monda-muki/web/seleniumqref in /home/users/1/monda-muki/web/seleniumqref.com/google-api-php-client-1-master/src/Google/Http/REST.php on line 110