🧪 Selenium · 레슨 3 / 6

Selenium 대기 전략 — 암묵적 대기 vs 명시적 대기, expected_conditions, 흔한 예외 해결

Selenium 테스트가 흔들리는 가장 큰 원인인 타이밍 문제를 해결합니다. time.sleep과 암묵적 대기의 한계, WebDriverWait와 expected_conditions로 명시적 대기하기, 사용자 정의 조건, 두 대기를 섞으면 안 되는 이유, NoSuchElement, StaleElementReference, ElementClickIntercepted 예외 원인과 해결을 배웁니다.

⏱ 약 4분🗓 2026-11-13 업데이트🏷 Selenium 4.x 기준

이 레슨에서 배우는 것

  • sleep·암묵적 대기 대신 명시적 대기 쓰기
  • expected_conditions와 사용자 정의 조건으로 기다리기
  • 자주 만나는 예외의 원인을 알고 해결하기

왜 기다려야 하나

Selenium은 Playwright·Cypress와 달리 자동으로 기다리지 않습니다(get()이 페이지 로드를 기다리는 것 정도). 버튼 클릭 후 API 응답을 받아 목록을 그리는 화면에서, 코드는 목록이 그려지기 전에 다음 줄을 실행해 NoSuchElementException을 냅니다. 로컬에서는 통과하고 CI에서는 실패하는 Selenium 테스트의 대부분이 이 문제입니다.

time.sleep은 답이 아니다

python
driver.find_element(By.ID, "search").click()
time.sleep(3)          # 1초면 될 때도 3초 낭비, 5초 걸리는 날엔 실패
driver.find_element(By.CSS_SELECTOR, ".result")

고정 대기는 항상 너무 길거나 너무 짧습니다. 테스트 200개에 3초씩이면 10분이 그냥 사라집니다.

암묵적 대기

python
driver.implicitly_wait(5)   # 세션 전체: find_element가 요소를 찾을 때까지 최대 5초 재시도

설정 한 줄로 모든 find_element에 적용되어 편하지만 한계가 있습니다.

명시적 대기: WebDriverWait

필요한 지점에서 구체적인 조건이 참이 될 때까지 기다립니다. 조건은 기본 0.5초 간격으로 확인합니다.

python
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

wait = WebDriverWait(driver, timeout=10)

button = wait.until(EC.element_to_be_clickable((By.ID, "submit")))   # 찾은 요소를 반환
button.click()

wait.until(EC.visibility_of_element_located((By.ID, "message")))
wait.until(EC.text_to_be_present_in_element((By.ID, "message"), "Received!"))
wait.until(EC.url_contains("/submitted"))
wait.until(EC.invisibility_of_element_located((By.CSS_SELECTOR, ".spinner")))
Javajava
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement button = wait.until(ExpectedConditions.elementToBeClickable(By.id("submit")));
button.click();
wait.until(ExpectedConditions.textToBePresentInElementLocated(By.id("message"), "Received!"));
조건 (Python)기다리는 것
presence_of_element_locatedDOM에 존재
visibility_of_element_located존재하고 화면에 보임
element_to_be_clickable보이고 활성화됨
invisibility_of_element_located사라지거나 숨겨짐 (로딩 스피너)
text_to_be_present_in_element요소 텍스트에 특정 문자열 포함
number_of_windows_to_be(n), alert_is_present()새 창, 알림창
frame_to_be_available_and_switch_to_itiframe 준비 후 전환까지
staleness_of(el)기존 요소가 DOM에서 떨어져 나감 (페이지 갱신 완료 신호)

사용자 정의 조건

until에는 드라이버를 받아 참 같은 값을 반환하는 함수를 넘길 수 있습니다. 반환값이 그대로 until의 결과가 됩니다.

python
# 목록이 5개 이상 그려질 때까지
rows = wait.until(lambda d: (r := d.find_elements(By.CSS_SELECTOR, "tbody tr")) and len(r) >= 5 and r)

# 진행 중인 fetch가 없을 때까지 (앱이 window.__pending 카운터를 노출하는 경우)
wait.until(lambda d: d.execute_script("return window.__pending === 0"))

# 특정 예외를 무시하며 재시도
from selenium.common.exceptions import StaleElementReferenceException
wait = WebDriverWait(driver, 10, poll_frequency=0.2, ignored_exceptions=[StaleElementReferenceException])
⛔
암묵적 대기와 명시적 대기를 섞지 마세요

공식 문서가 명시적으로 경고하는 부분입니다. 암묵적 대기 10초 + 명시적 대기 15초를 함께 쓰면, 명시적 대기 안에서 호출되는 find_element마다 암묵적 대기가 걸려 실제 대기 시간이 예측 불가능해집니다(20초 이상이 되기도 합니다). 암묵적 대기는 0으로 두고 명시적 대기만 쓰는 것을 권장합니다.

흔한 예외와 해결

예외원인해결
NoSuchElementException아직 렌더링 전, 셀렉터 오류, iframe 안에 있음명시적 대기, 개발자 도구로 셀렉터 확인, switch_to.frame
StaleElementReferenceException찾아 둔 요소가 재렌더링으로 DOM에서 교체됨동작 직전에 다시 찾기. 요소 대신 로케이터를 보관
ElementClickInterceptedException로딩 오버레이·쿠키 배너·고정 헤더가 가림오버레이가 사라질 때까지 대기, 스크롤, 배너는 쿠키로 미리 닫기
ElementNotInteractableException숨겨져 있거나 크기가 0element_to_be_clickable, 창 크기 확인(헤드리스 기본 창이 작음)
TimeoutException명시적 대기 조건이 끝내 참이 안 됨조건이 맞는지, 실제로 기능이 동작하는지 스크린샷으로 확인
python
# Stale 방지: 요소를 저장해 두지 말고 로케이터를 저장
ROW_DELETE = (By.CSS_SELECTOR, "tr[data-id='42'] button.delete")
wait.until(EC.element_to_be_clickable(ROW_DELETE)).click()
⚠️
JavaScript 클릭은 최후의 수단

driver.execute_script("arguments[0].click()", el)는 가림·숨김 검사를 건너뛰어 실패를 숨깁니다. 사용자가 클릭할 수 없는 상태인데 테스트는 통과하는 상황이 생길 수 있으니, 원인(오버레이, 창 크기)을 먼저 해결하세요.

정리