トップページ > 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: (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