Selenium - expected conditions

헨도·2022년 12월 12일
0

Selenium

목록 보기
1/4
post-thumbnail

Python

expected_conditions

expected_conditions 는 조건을 설정하고 조건에 부합하는지 안하는지 판단한다.

expected_conditions 는 사용하기 위해 import가 필요하다.

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

expected_conditions 를 도와주는 명령어

WebDriverWait

WebDriverWait(driver, 초) 는 WebDriverWait 을 통해 driver를 "최대" 정해진 시간동안 기다린다.
(이 때, 정해진 시간을 넘기면 NoSuchElementException, ElementNotVisibleException 과 같은 에러 발생)

Ex.
WebDriverWait(driver, 10)

By

By는 확인하려는 요소가 어떤 속성인지 정의하고, "" 안에 확인하려는 요소의 경로나 이름을 넣으면 된다.

Ex.
.presence_of_element_located((By.CSS_SELECTOR, "선택자 경로")

위의 명령어와 같이 지정한 선택자 요소가 현재 페이지에 있는지 확인하는 조건이다.

이 외 다른 조건들이 존재하는데, 주로 쓰이는 것만 보겠다.

1. 로딩된 페이지에 조건 요소가 있는지 확인
expected_conditions.presence_of_element_located((By., ""))

2. 로딩된 페이지에 조건 요소가 보이는지 확인
expected_conditions.visibility_of_element_located((By., ""))

3. 로딩된 페이지가 조건 요소 중 하나라도 있는지 확인
expected_conditions.presence_of_all_elements_located((By., ""))

4. 조건 요소가 클릭 가능한지 확인
expected_conditions.element_to_be_clickable((By., ""))

.until()

언제까지? 라는 조건을 주기 위한 명령어이다.

Ex. .until(EC.presence_of_element_located((By.ID, "Example"))
  • EC = expected_conditions

위의 명령어가 실행되면, ID 값이 Example인 요소가 나올 때까지 대기한다.
이 때, 해당 요소가 나오면 EC에서 True를 반환한다.

즉, ID가 Example인 요소가 나올 때까지 지정한 시간만큼 기다린다.

expected_conditions 특징

  • expected_conditions 는 조건 자체이기에 단독으로 사용할 수 없다.
  • 조건이 부합할 때까지 기다리는 전체 코드는 아래의 명령어와 같다.
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

WebDriverWait(dr, 5).until(EC.presence_of_element_located(By.CSS_SELECTOR, "선택자 경로"))
  • expected_conditions와 WebDriverWait은 짧은 이름으로 자주 정의하는 편이다.
profile
Junior Backend Developer

0개의 댓글