LoginSignup
133

More than 5 years have passed since last update.

Seleniumで待機処理するお話

Posted at

Seleniumで待機処理するお話

Webページを開く

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException

#ここではEdgeを使っています
driver = webdriver.Edge(executable_path='C:\\...\\MicrosoftWebDriver.exe')
driver.get('https://www.yahoo.co.jp/')

Webページ上のコンテンツを基準にした待機例

# ページ上のすべての要素が読み込まれるまで待機(15秒でタイムアウト判定)
WebDriverWait(driver, 15).until(EC.presence_of_all_elements_located)

# ID指定したページ上の要素が読み込まれるまで待機(15秒でタイムアウト判定)
WebDriverWait(driver, 15).until(EC.presence_of_element_located((By.ID, 'ID名')))

# CLASS名指定したページ上の要素が読み込まれるまで待機(15秒でタイムアウト判定)
WebDriverWait(driver, 15).until(EC.presence_of_element_located((By.CLASS_NAME, 'CLASS名')))

# try/catch例
try:
    WebDriverWait(driver, 15).until(EC.presence_of_all_elements_located)
except TimeoutException as te:
    ### 例外処理

時間指定の待機例

# 一度設定すると find_element 等の処理時に、
# 要素が見つかるまで指定時間繰り返し探索するようになります。
driver.implicitly_wait(10) # 秒
targetElement = driver.find_element_by_id("ID名")

よくある Stale Element Reference Exception

この例外は、Webページ上のロードが不完全な場合に、Seleniumで要素を触りにいった時に発生します。基本的には、上記の待機処理で試行錯誤するお話になりますが、Seleniumで捉えきれない動的なコンテンツや要素である場合には、HTMLのコードをSeleniumよりに修正するか、最終手段としてtime.sleep()を使うかも検討しています。

参考

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
133