Python/Selenium

Selenium CoordinatesOutOfBoundsException 오류 해결하기

PySun 2025. 1. 31. 08:44
반응형

소개

Selenium을 사용하여 웹 자동화를 하는 과정에서 'CoordinatesOutOfBoundsException' 오류는 발생할 수 있는 일반적인 문제입니다. 이 오류는 Selenium이 지정된 위치가 웹 페이지의 범위를 벗어나거나 존재하지 않는 위치를 클릭하려고 할 때 발생합니다. 웹 페이지의 요소가 예상과 다르게 로드되어 있거나, 화면의 크기 문제로 인한 경우가 많습니다. 이번 블로그 글에서는 이 오류의 원인과 해결 방법에 대해 살펴보겠습니다.

에러 발생 예시 코드

먼저, 'CoordinatesOutOfBoundsException' 오류가 발생할 가능성이 있는 간단한 예시 코드를 살펴보겠습니다.

from selenium import webdriver
from selenium.webdriver.common.by import By

# Chrome 웹드라이버 실행
driver = webdriver.Chrome()

# 테스트할 웹 페이지 열기
driver.get('https://example.com')

# 존재하지 않는 좌표 클릭 시도
driver.execute_script("window.scrollTo(0, 500);")
element = driver.find_element(By.TAG_NAME, 'body')
element.click()  # 원하지 않는 좌표에 클릭 시도

에러 해결 방법

1. 요소의 존재 여부 확인

Selenium을 통해 클릭하려는 요소가 실제로 페이지에 존재하는지 확인하는 것이 중요합니다. 모든 요소가 의도한 대로 로드되기를 기다리세요.

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.element_to_be_clickable((By.TAG_NAME, 'body'))
    )
    element.click()  # 클릭 시도
except Exception as e:
    print(e)
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

# Chrome 웹드라이버 실행
driver = webdriver.Chrome()

# 웹 페이지 열기
driver.get('https://example.com')

# 특정 이미지 요소 확인 후 클릭
try:
    image = WebDriverWait(driver, 10).until(
        EC.visibility_of_element_located((By.CSS_SELECTOR, 'img.some-class'))
    )
    image.click()
except Exception as e:
    print(e)
finally:
    driver.quit()

마무리

이번 블로그에서는 Selenium에서 발생하는 'CoordinatesOutOfBoundsException' 오류에 대한 몇 가지 해결 방법을 살펴보았습니다. 웹 페이지의 요소가 정확히 로드되었는지 확인하고, 스크롤이나 대기 기능을 통해 오류를 극복할 수 있습니다. 이러한 점들을 유념하여 올바른 웹 자동화 작업을 수행하시기 바랍니다. 항상 최신 문서를 참고하고 에러에 대한 해결법을 적극적으로 찾아보세요!

반응형