소개
Selenium을 사용하여 웹 자동화를 진행하다 보면 'Element is not attached to the page document'라는 오류에 부딪힐 수 있습니다. 이 오류는 Selenium이 참조하는 요소가 현재 DOM에서 사라졌을 때 발생합니다. 즉, 페이지가 업데이트되거나 동적으로 변화하면서 해당 요소가 더 이상 존재하지 않게 되는 것이죠. 이번 블로그에서는 이 오류가 발생하는 원인과 해결 방법에 대해 알아보겠습니다.
에러 발생 예시 코드
먼저, 'Element is not attached to the page document' 오류가 발생할 수 있는 간단한 예시 코드를 살펴볼까요.
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
# 웹드라이버 인스턴스 생성
driver = webdriver.Chrome()
# 특정 URL 접속
driver.get('https://example.com')
# 요소를 찾고 클릭
element = driver.find_element(By.XPATH, '//button[@id="myButton"]')
element.click()
# 요소를 다시 찾으려고 할 때 (페이지가 새로고침 등의 이유로 DOM이 변경됨)
time.sleep(5) # 페이지가 업데이트 되는 시간 대기
element.click() # 오류 발생 가능성 있음
에러 해결 방법
1. 요소 재선택하기
DOM이 변경되었을 경우, 기존 요소를 사용하기보다는 새롭게 요소를 선택하는 방법이 좋습니다. 다음은 새로운 방법으로 요소를 찾는 예시입니다.
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
driver = webdriver.Chrome()
driver.get('https://example.com')
# 버튼 클릭
button = driver.find_element(By.XPATH, '//button[@id="myButton"]')
button.click()
# 페이지 업데이트 대기
time.sleep(5)
# 다시 요소 찾기
button = driver.find_element(By.XPATH, '//button[@id="myButton"]')
button.click() # 이제는 오류가 발생하지 않음
2. 명시적 대기 사용하기
요소가 페이지에 로드될 때까지 기다리는 명시적 대기를 사용하면 오류를 줄일 수 있습니다. WebDriverWait을 이용하여 특정 조건이 충족될 때까지 기다리는 방식입니다.
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('https://example.com')
# 버튼 클릭
button = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, '//button[@id="myButton"]'))
)
button.click()
# 페이지 업데이트 대기
button = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, '//button[@id="myButton"]'))
)
button.click() # 오류가 발생하지 않음
마무리
이번 블로그 포스트에서는 Selenium에서 'Element is not attached to the page document'이라는 오류를 해결하는 다양한 방법을 살펴보았습니다. 요소를 재선택하거나 명시적 대기를 활용하여 코드의 신뢰성을 높일 수 있습니다. 웹 자동화를 진행할 때, 항상 페이지의 상태와 요소의 변경을 고려하며 코드를 작성하는 것이 중요합니다. 문제가 발생하면 주저하지 말고 이와 같은 해결 방법을 참고하여 오류를 극복해 보세요!
'Python > Selenium' 카테고리의 다른 글
Selenium.close로 현재 탭 닫기 (0) | 2025.01.16 |
---|---|
Selenium Error: session deleted because of page crash 해결하기 (0) | 2025.01.15 |
Selenium Element Has No Attribute 오류 해결하기 (0) | 2025.01.15 |
Selenium.drag으로 요소 드래그하기 (0) | 2025.01.15 |
Selenium find_by_partial_link_text로 부분 링크 텍스트로 요소 찾기 (0) | 2025.01.15 |