반응형
소개
Selenium을 사용할 때, 'NoSuchDocumentException' 오류는 자주 발생하는 문제 중 하나입니다. 이 오류는 브라우저에서 HTML 문서나 요소를 찾지 못할 때 발생합니다. 특히 동적 페이지나 비동기식 로딩이 이루어지는 웹사이트를 자동화할 때 이 오류를 자주 만나게 됩니다. 이번 블로그 글에서는 이 에러의 원인과 해결 방법을 함께 알아보겠습니다.
에러 발생 예시 코드
먼저, 'NoSuchDocumentException' 오류가 발생할 수 있는 간단한 예제 코드를 살펴보겠습니다.
from selenium import webdriver
from selenium.common.exceptions import NoSuchDocumentException
# Chrome 웹 드라이버 초기화
driver = webdriver.Chrome()
# 특정 웹페이지로 이동
driver.get("https://example.com")
# 존재하지 않는 요소 찾기 (예: 문서가 로드되지 않거나 비동기 로딩 중)
element = driver.find_element_by_id("non_existing_id")
print(element.text)
에러 해결 방법
1. 웹페이지가 완전히 로드되었는지 확인하기
비동기식 로딩으로 인해 모든 요소가 로드되지 않을 수 있습니다. 이러한 경우, 특정 요소가 로드될 때까지 명시적으로 기다려야 합니다.
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
# Chrome 웹 드라이버 초기화
driver = webdriver.Chrome()
# 특정 웹페이지로 이동
driver.get("https://example.com")
# 특정 요소가 로드될 때까지 대기
try:
element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, "non_existing_id"))
)
print(element.text)
except NoSuchDocumentException:
print("문서가 존재하지 않거나 로드되지 않았습니다.")
2. 요소의 존재 여부를 확인하기
요소를 찾기 전에 문서나 특정 요소가 존재하는지 먼저 확인하는 것도 좋은 방법입니다.
from selenium import webdriver
# Chrome 웹 드라이버 초기화
driver = webdriver.Chrome()
# 특정 웹페이지로 이동
driver.get("https://example.com")
# 특정 요소의 존재 여부 확인
try:
element = driver.find_element_by_id("non_existing_id")
print(element.text)
except NoSuchDocumentException:
print("해당 문서가 존재하지 않습니다.")
except Exception as e:
print(f"예기치 않은 오류 발생: {e}")
마무리
오늘은 Selenium을 사용할 때 발생할 수 있는 'NoSuchDocumentException' 오류의 원인과 해결 방법에 대해 알아보았습니다. 비동기식 로딩이나 요소의 존재 여부를 잘 살펴보며, 올바르게 대기하는 방법을 통해 이러한 오류를 피할 수 있습니다. Selenium을 활용하여 웹 자동화 작업을 수행할 때는 안정성을 유지하며 코드를 작성하는 것이 중요합니다.
반응형
'Python > Selenium' 카테고리의 다른 글
selenium.webdriver.refresh로 페이지 새로고침하기 (0) | 2025.01.26 |
---|---|
selenium TooManyRequestsException 오류 해결하기 (0) | 2025.01.25 |
selenium NoRubyException 오류 해결하기 (0) | 2025.01.25 |
selenium.webdriver.quit으로 브라우저 종료하기 (0) | 2025.01.25 |
selenium.webdriver.page_source로 페이지 소스 얻기 (0) | 2025.01.25 |