반응형
Selenium WebDriver의 until_not: 요소 비활성 상태 대기하기
웹 자동화에서 가장 중요하고 때때로 어려운 부분 중 하나는 페이지의 동적 요소를 처리하는 것입니다. Selenium WebDriver의 until_not 메서드는 특정 요소가 비활성화될 때까지 대기할 수 있는 방법을 제공합니다. 이 포스팅에서는 until_not 메서드의 사용법과 함께 실제 예제를 소개하겠습니다.
until_not 메서드 소개
until_not 메서드는 제공된 조건이 만족되지 않을 때까지 대기합니다. 보통 특정 요소가 비활성 상태일 때, 해당 상태가 변경되기를 기다리는 데 사용됩니다. 이 기능은 특히 AJAX 요청이나 자바스크립트가 페이지를 업데이트하는 경우에 유용합니다.
함수 시그니처
WebDriverWait(driver, timeout).until_not(expected_conditions)
매개변수:
- driver: Selenium WebDriver 인스턴스입니다.
- timeout: 대기할 최대 시간(초)입니다.
- expected_conditions: 만족되지 않을 조건을 지정하는 함수입니다.
반환 값:
- 조건이 만족되지 않을 때까지 대기한 후, 조건이 충족된 후 return 됩니다. 조건이 충족되지 않으면 TimeoutException이 발생합니다.
사용 예제
버튼 비활성 예제
다음은 특정 버튼이 비활성화될 때까지 대기하는 간단한 예제입니다.
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')
# 특정 요소의 비활성 상태 대기 (예: 버튼)
button = driver.find_element(By.ID, 'submit-button')
# 버튼이 비활성화될 때까지 대기
WebDriverWait(driver, 10).until_not(EC.element_to_be_clickable((By.ID, 'submit-button')))
print("버튼이 비활성화되었습니다.")
# 드라이버 종료
driver.quit()
AJAX 요청 후 요소 비활성 대기 예제
AJAX 요청 후에 요소가 비활성 상태를 가지는 경우를 처리하는 예제를 살펴보겠습니다.
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')
# AJAX 요청을 트리거하는 버튼 클릭
trigger_button = driver.find_element(By.ID, 'ajax-trigger')
trigger_button.click()
# 특정 AJAX 로딩 인디케이터가 사라질 때까지 대기
loading_indicator = (By.CSS_SELECTOR, '.loading')
WebDriverWait(driver, 10).until_not(EC.presence_of_element_located(loading_indicator))
print("AJAX 요청이 완료되었습니다.")
# 드라이버 종료
driver.quit()
결론
until_not 메서드는 웹 자동화 시 동적 요소를 처리하는 데 매우 유용한 도구입니다. 페이지 로딩이나 AJAX 요청 등에서 발생할 수 있는 비동기 동작을 제어하여 더욱 안정적인 자동화 스크립트를 작성할 수 있게 합니다. 이를 통해 여러분의 웹 스크래핑 및 테스트 작업이 더욱 효율적으로 이루어질 수 있습니다.
- 비활성 상태를 대기하여 웹 자동화를 보다 정교하게 만들어 보세요!
- 지금 바로 until_not을 활용하여 동적 웹 요소를 처리해 보세요!
반응형
'Python > Selenium' 카테고리의 다른 글
Selenium ChromeDriverServiceNotFoundException 오류 해결하기 (0) | 2025.01.31 |
---|---|
Selenium BrowserVersionMismatchException 오류 해결하기 (0) | 2025.01.31 |
selenium.webdriver.wait.until로 조건 대기하기 (0) | 2025.01.31 |
selenium.webdriver.wait로 요소 대기하기 (0) | 2025.01.31 |
selenium WebDriverServerException 오류 해결하기 (0) | 2025.01.30 |