⫸IT|SmartTech/파이썬

selenium에서 암시적(implicit) VS 명시적(explicit) 대기의 차이점 및 사용법(feat. time)

OSMU-PIPELINE 2023. 7. 1. 21:54
반응형

selenium을 사용하다 보면 대기하는 시간을 활용하게 되는데 그중에는 대표적으로 3가지 방법이 있다.

1. time.sleep() : time 모듈 사용

from selenium import webdriver
import time

driver = webdriver.Chrome()
driver.get('https://wwww.naver.com')
time.sleep(10)

가장 대표적인 방법으로 지정한 시간 만큼 대기하는 방법이다.

가장 쉬운 방법이긴 하지만 이미 페이지 로딩이 끝났음에도 지정한 시간만큼 계속 대기해야 하는 loss time이 발생한다.


2. 암시적 대기(implicitly wait) : implicitly_wait() 메서드 사용

*특정 조건을 명시하지 않음

from selenium import webdriver

driver = webdriver.Chrome()
driver.get('https://wwww.naver.com')
driver.implicitly_wait(10)

.implicitly_wait(10)의 뜻은 네이버의 페이지 로딩이 끝날 때까지 최대 10초까지 기다린다는 뜻으로,

로딩이 끝나는 대로 다음 명령어를 수행하며, 10초가 넘어갈 동안 페이지 로딩이 끝나지 않는다면 다음 명령어를 수행하게 된다.


3. 명시적 대기(explicitly wait) : WebDriverWait, expected_conditions, By 필요

*특정 조건을 명시함

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://www.naver.com')
wait = WebDriverWait(driver, 10)  # Wait for a maximum of 10 seconds

element = wait.until(EC.presence_of_element_located((By.ID, 'myElement')))

명시적 대기는 특정 조건이 발생할 때까지 대기하는 기능을 제공하고 있어 암시적 대기보다 세밀한 제어를 할 수 있다.

예를 들어, 네이버에 로그인을 하고 싶다면 페이지의 모든 요소가 나타날때까지 대기하는 것이 아닌 로그인 창에 대한 요소들의 로딩이 끝날 때까지만 대기하면 된다.

이처럼 페이지를 구성하고 있는 특정 요소가 사용자가 정한 조건에 부합할 때까지 대기할 경우에 사용한다.

.until(EC.presence_of_element_located((By.ID,'myElement')))

위의 부분이 사용자가 정하는 조건을 설정하는 부분이며,

presence_of_element_located((By.ID, 'myElement'))는 'myElement'라는 요소가 나타날 때까지 대기한다라는 뜻을 가진다.

 

요소의 상태에 따라 사용자가 정하는 조건에는 다음과 같이 다양한 방식들이 존재한다.

EC.title_is(...)
EC.title_contains(...)
EC.presence_of_element_located(...)
EC.visibility_of_element_located(...)
EC.visibility_of(...)
EC.presence_of_all_elements_located(...)
EC.text_to_be_present_in_element(...)
EC.text_to_be_present_in_element_value(...)
EC.frame_to_be_available_and_switch_to_it(...)
EC.invisibility_of_element_located(...)
EC.element_to_be_clickable(...)
EC.staleness_of(...)
EC.element_to_be_selected(...)
EC.element_located_to_be_selected(...)
EC.element_selection_state_to_be(...)
EC.element_located_selection_state_to_be(...)
EC.alert_is_present(...)

다시한번 요약하자면, 암시적 대기는 사용자의 특정한 조건 없이 모든 요소에 대한 전역 대기 시간을 설정하는 반면 명시적 대기는 사용자의 특정 조건을 명시(정의)하고 그 조건에 부합할 때까지의 대기시간을 설정하는 것이다.

 

위의 세가지 방법 중 어떤 것이 가장 좋다고 할 수 없으며 상황에 따라 적절하게 사용하면 될 것이다.

반응형