tapitapi’s blog

1日1杯タピオカ!エンジニア

【Selenium】WebDriverWaitで複数の条件を指定する

SeleniumのWebDriverで、

ある条件になるまで待機するWebDriverWait関数に、複数の条件を指定する方法

 

通常、条件を一つ指定する例は下記のようになる。(id="someid" の要素がクリックできるまで待つ。10秒経ってもクリックできるようにならなかったら、例外エラー発生)

from selenium.webdriver.support import expected_conditions as EC

wait = WebDriverWait(driver, 10)
element = wait.until(EC.element_to_be_clickable((By.ID, 'someid')))

 

複数は、or, and, not (python logical operators の詳細はこちら)で繋げればOK

 

(id="error"の要素か、class="fail"の要素が現れるまで待って、スクリーンショットを取得する例)

from selenium.webdriver.support import expected_conditions as EC

 

wait = WebDriverWait(self.driver,10)

wait.until(

(ExpectedConditions.visibility_of_element_located((By.ID, 'error')))

or

(ExpectedConditions.visibility_of_element_located((By.CLASS_NAME, 'fail')))

)

self.driver.save_screenshot('result1.png')

 

untilの中はif文の条件と同じように記載すればOK!

ということですね(記事にするまでもなかったんじゃ、、、?というツッコミは無しにして、、、お役に立てば幸いです。)

 

今日はここまでーーー

 

おやすみなさいぃぃぃ