콘솔워크

[selenium] EC(Expected Conditions)과 while문을 활용해 반복작업 하기 본문

프로그래밍/python

[selenium] EC(Expected Conditions)과 while문을 활용해 반복작업 하기

이휘재123 2022. 8. 10. 15:23
반응형
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC   
   
   
def confirm_start(self):
    driver = self.driver

    have_list = True
    while have_list:

        try:
            self.get_order_list()
        except Exception as e:
            print(f"주문 목록 로드 실패")
            have_list = False
            break

        # 목록 로딩 대기
        WebDriverWait(driver, 5).until(
            EC.presence_of_element_located((By.CSS_SELECTOR, "#TBL_LIST tr"))
        )
        time.sleep(0.5)

        try:
            driver.implicitly_wait(5)
            order_link = driver.find_element(By.CSS_SELECTOR, "#TBL_LIST tr a")
            order_link.click()

            # 작업영역 -> 구매확정
            self.confirm_order()
            time.sleep(1)

        except Exception as e:
            print(f"더 이상 물품이 없습니다.")
            have_list = False
            continue

        finally:
            driver.implicitly_wait(self.default_wait)

    time.sleep(1)

위 코드는 테이블의 tr에 링크가 있는지 검색해보고 있는 경우에는 작업을, 없는 경우에는 except가 발생하여 반복문을 탈출하는 식으로 작업하였다.

 

만약 사이트 로딩상의 문제로

WebDriverWait(driver, 5).until(EC.presence_of_element_located((By.CSS_SELECTOR, "#TBL_LIST tr"))) 의 요소가 검색되었지만 클릭이 불가능한 경우에는

 

EC.element_to_be_clickable 을 사용해 해당 요소가 클릭이 가능한 상태인지로 바꿔주면 된다.

 

 

 

EC(Expected Conditions) 메소드 참고자료

https://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.support.expected_conditions

 

7. WebDriver API — Selenium Python Bindings 2 documentation

A single IP address, as a string. If any IPv4 address is found, one is returned. Otherwise, if any IPv6 address is found, one is returned. If neither, then None is returned.

selenium-python.readthedocs.io

 

반응형