본문 바로가기
Python/Selenium

파이썬 Selenium WebDriverTimeoutException 오류 해결하기

by PySun 2023. 8. 25.
반응형

WebDriverTimeoutException은 웹 드라이버가 지정된 시간 내에 요청한 작업을 완료하지 못할 때 발생하는 예외입니다. 예를 들어, 요소를 찾는데 지정된 시간 내에 해당 요소가 나타나지 않는 경우 발생할 수 있습니다. 예시 코드와 해결 방법에 대해 설명하겠습니다.

예시 코드:

아래 예시 코드에서는 WebDriverTimeoutException이 발생할 수 있는 상황을 보여줍니다. 요소가 지정된 시간 내에 나타나지 않는 경우를 시뮬레이션한 것입니다.

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

try:
    driver = webdriver.Chrome('path/to/chromedriver')

    # 요소를 찾는데 시간 초과 설정
    driver.get('https://www.example.com')
    wait = WebDriverWait(driver, 5)  # 5초 동안 기다림
    element = wait.until(EC.presence_of_element_located((By.ID, 'non_existent_element')))

except WebDriverTimeoutException as e:
    print("WebDriverTimeoutException이 발생했습니다:", str(e))
finally:
    # 브라우저 종료
    driver.quit()

해결 방법:

WebDriverTimeoutException이 발생할 때 다음과 같은 방법으로 처리할 수 있습니다.

대기 시간 조정:

WebDriverWait를 사용하여 요소를 찾을 때 사용되는 대기 시간을 조정합니다. 기본적으로 5초 대기 후 요소가 나타나지 않으면 TimeoutException이 발생합니다. 대기 시간을 늘리거나 줄여서 요소의 나타나는 속도에 맞게 조정할 수 있습니다.

from selenium.webdriver.support.ui import WebDriverWait

# 대기 시간 조정 예시
wait = WebDriverWait(driver, 10)  # 10초 동안 기다림
element = wait.until(EC.presence_of_element_located((By.ID, 'element_id')))

조건 조정:

WebDriverWait와 expected_conditions를 사용할 때 확인 조건을 조정하여, 요소가 나타날 때까지 기다리거나, 나타나지 않아도 예외가 발생하지 않도록 조정할 수 있습니다.

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# 조건 조정 예시
wait = WebDriverWait(driver, 10)
element = wait.until(EC.presence_of_element_located((By.ID, 'element_id')))

WebDriverTimeoutException이 발생한 경우 대기 시간과 확인 조건을 조정하여, 요소가 나타날 때까지 기다릴 수 있도록 합니다. 웹 페이지의 상황에 따라 적절한 대기 시간과 확인 조건을 설정하여 예외를 처리하도록 합니다.

반응형