Python/Selenium

Selenium SyncTimeoutException 해결하기

PySun 2025. 2. 18. 08:27
반응형

소개

웹 자동화 도구인 Selenium을 사용할 때 가끔 'SyncTimeoutException' 에러가 발생하는 경우가 있습니다. 이 오류는 Selenium이 지정된 시간 내에 웹 페이지의 특정 요소를 찾지 못했을 때 발생합니다. 이 블로그 글에서는 'SyncTimeoutException' 에러의 원인과 이를 해결하기 위한 몇 가지 방법에 대해 다루어 보겠습니다.

에러 발생 예시 코드

먼저, 'SyncTimeoutException' 오류가 발생할 가능성이 있는 간단한 예시 코드를 살펴봅시다.

from selenium import webdriver
from selenium.common.exceptions import TimeoutException

# 웹 드라이버 초기화
driver = webdriver.Chrome()

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

    # 요소 찾기 (예: 존재하지 않는 버튼)
    button = driver.find_element_by_id("non_existent_button")
    button.click()
except TimeoutException as e:
    print("타임아웃 오류 발생:", e)
finally:
    driver.quit()

에러 해결 방법

1. 명시적 대기(Explicit Wait) 사용하기

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
from selenium.common.exceptions import TimeoutException

# 웹 드라이버 초기화
driver = webdriver.Chrome()

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

    # 명시적 대기 사용하여 요소 찾기
    button = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, "non_existent_button"))
    )
    button.click()
except TimeoutException as e:
    print("타임아웃 오류 발생:", e)
finally:
    driver.quit()

2. 페이지 로딩 완료 대기하기

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
from selenium.common.exceptions import TimeoutException

# 웹 드라이버 초기화
driver = webdriver.Chrome()

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

    # 페이지 로드 완료 대기
    WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.TAG_NAME, 'body'))  # 몸체 태그가 로드될 때까지 대기
    )

    # 요소 찾기
    button = driver.find_element(By.ID, "non_existent_button")
    button.click()
except TimeoutException as e:
    print("타임아웃 오류 발생:", e)
finally:
    driver.quit()

마무리

이 블로그 글에서는 Selenium에서 발생하는 'SyncTimeoutException' 에러에 대한 해결 방법을 살펴보았습니다. 명시적 대기를 활용하거나 페이지 로딩 완료를 확인하는 방법을 통해 이 오류를 피할 수 있습니다. 항상 웹 페이지의 상태와 요소의 로딩을 확인하는 것이 중요합니다. 여러분의 웹 자동화 작업이 더 매끄럽게 진행되기를 바랍니다!

반응형