Python/Selenium
Selenium ElementStateChangeException 오류 해결하기
PySun
2025. 2. 23. 08:12
반응형
소개
Selenium을 사용하여 웹 자동화를 하다 보면 때때로 'ElementStateChangeException' 오류가 발생할 수 있습니다. 이 오류는 일반적으로 웹 페이지의 요소 상태가 변경되었을 때 발생하며, 예를 들어 버튼이 비활성화되거나 DOM이 동적으로 변경되는 경우에 주로 발생합니다. 이번 글에서는 이 오류의 원인과 해결 방법에 대해 알아보겠습니다.
에러 발생 예시 코드
먼저, 'ElementStateChangeException' 오류가 발생할 수 있는 간단한 예시 코드를 살펴보겠습니다.
from selenium import webdriver
from selenium.common.exceptions import ElementStateChangeException
driver = webdriver.Chrome()
driver.get('http://example.com')
# 비활성화된 버튼 클릭 시도
button = driver.find_element_by_id('disabled-button')
button.click() # 이 부분에서 ElementStateChangeException이 발생할 수 있습니다.
에러 해결 방법
1. 요소의 상태를 확인하기
요소가 클릭할 수 있는 상태인지, 즉 활성화되어 있는지 확인하는 것이 중요합니다. 이를 위해 'is_enabled()' 메서드를 사용할 수 있습니다.
from selenium import webdriver
driver = webdriver.Chrome()
driver.get('http://example.com')
button = driver.find_element_by_id('disabled-button')
if button.is_enabled():
button.click()
else:
print("버튼이 비활성화되어 있습니다.")
2. 명시적 대기(Explicit Wait) 사용하기
요소의 상태 변화에 따라 기다릴 수 있도록 명시적 대기를 설정하는 것이 좋습니다. 다음은 이를 이용한 예시입니다.
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
driver = webdriver.Chrome()
driver.get('http://example.com')
# 명시적 대기 사용: 버튼이 클릭 가능해질 때까지 대기
button = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, 'disabled-button')))
button.click()
마무리
이번 블로그 글에서는 Selenium을 사용하다가 발생할 수 있는 'ElementStateChangeException' 오류에 대해 살펴보았습니다. 요소의 상태를 확인하거나 명시적 대기를 설정함으로써 이 오류를 극복할 수 있습니다. 웹 자동화를 할 때는 항상 페이지의 동적 변화에 유의하고, 적절한 방법으로 요소 상태를 점검하여 원활한 작업 진행을 보장하는 것이 중요합니다.
반응형