반응형
소개
Selenium을 사용하다가 'NotFoundException' 오류가 발생하는 경우, 이는 종종 웹 페이지에서 찾고자 하는 요소가 존재하지 않거나 올바른 방법으로 접근하지 못했을 때 발생합니다. 이러한 오류는 특히 동적인 웹사이트에서 흔히 발생할 수 있습니다. 이 글에서는 이 오류의 발생 원인과 해결 방법에 대해 알아보겠습니다.
에러 발생 예시 코드
먼저, 'NotFoundException' 오류가 발생할 수 있는 간단한 코드 예제를 살펴보겠습니다.
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
# 웹드라이버 생성
driver = webdriver.Chrome()
# 특정 웹사이트 열기
driver.get("https://example.com")
# 요소 접근 시도 (존재하지 않는 요소)
try:
element = driver.find_element_by_id("non_existent_id")
print(element.text)
except NoSuchElementException:
print("해당 요소를 찾을 수 없습니다.")
finally:
driver.quit()
에러 해결 방법
1. 요소의 존재 유무 확인
가장 먼저 시도해볼 수 있는 방법은 찾고자 하는 요소가 실제로 HTML에 존재하는지 확인하는 것입니다. 다양한 이유로 요소가 로드되지 않았을 수 있습니다.
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
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")
# 요소 존재 확인 (대기 후 접근)
try:
element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, "some_existing_id"))
)
print(element.text)
except NoSuchElementException:
print("해당 요소를 찾을 수 없습니다.")
finally:
driver.quit()
2. 적절한 대기 시간 설정
동적인 웹사이트에서는 요소가 로드되는 데 시간이 걸릴 수 있습니다. 그러므로 요소가 로드될 때까지 대기하는 코드로 수정할 필요가 있습니다.
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")
# 요소 대기 후 접근
try:
element = WebDriverWait(driver, 10).until(
EC.visibility_of_element_located((By.ID, "some_visible_id"))
)
print(element.text)
except Exception as e:
print(f"오류 발생: {e}")
finally:
driver.quit()
마무리
이 블로그 글에서는 Selenium에서 발생하는 'NotFoundException' 오류의 원인과 해결 방법을 다루어 보았습니다. 요소의 존재 유무를 확인하고, 적절한 대기 조건을 설정하여 해당 오류를 피할 수 있습니다. Selenium은 웹 자동화의 강력한 도구이지만, 적절한 예외 처리와 대기 전략이 필수적이라는 것을 잊지 마세요. 더욱 안정적인 자동화 스크립트를 위한 지속적인 학습이 필요합니다.
반응형
'Python > Selenium' 카테고리의 다른 글
selenium.webdriver.find_element_by_xpath 활용하기 (0) | 2025.01.22 |
---|---|
selenium.webdriver.find_element_by_partial_link_text 사용하기 (0) | 2025.01.22 |
Selenium NoSuchAttributeException 오류 해결하기 (0) | 2025.01.21 |
Selenium WebDriver cannot be instantiated 오류 해결하기 (0) | 2025.01.21 |
selenium.webdriver.find_element_by_name로 요소 찾기 (0) | 2025.01.21 |