2024.03.26(화)

🤖Selenium

브라우저 자동화 도구
Selenium automates browsers. That's it!

🔧Selenium 구성 요소

  • Selenium Web Driver
    • 브라우저 자동화 드라이버
    • 시중 브라우저들에 대한 라이브러리를 제공
  • Selenium IDE
    • 웹-사용자 상호작용을 기록(녹화)하고 재생하여 테스트 자동화에 활용
    • Chrome 및 Firefox의 extension으로 설치 및 이용
  • Selenium Grid
    • 분산 환경을 구성하여 hub가 요청을 수신, node 들에 테스트 수행을 분배하고 결과 수집
    • WebDriver 스크립트를 다수의 테스트 머신에 병렬 적용하여 테스트를 가속하고 효율화

🚶‍♂️Selenium standalone(hub + node) 실습

🐋selenium standalone 도커에 실행

  • 도커 이미지: selenium/standalone-chrome (ARM 기반 환경은 seleniarm/standalone-chromium)

  • 서비스 노출 포트: 4444

    docker run -d --rm -p 4444:4444 -v /dev/shm:/dev/shm selenium/standalone-chrome
  • http://localhost:4444에 접속해서 확인

🐍Selenium python 라이브러리 설치

☘️Selenium 기초

  • 특정 조건을 만족할 때까지 기다린 후 test 진행하도록 하기
  • 다양한 locator로 문서에서 원하는 요소를 찾기
    LocatorDescription
    class nameLocates elements whose class name contains the search value (compound class names are not permitted)
    css selectorLocates elements matching a CSS selector
    idLocates elements whose ID attribute matches the search value
    nameLocates elements whose NAME attribute matches the search value
    link textLocates anchor elements(<a>) whose visible text matches the search value
    partial link textLocates anchor elements(<a>) whose visible text contains the search value. If multiple elements are matching, only the first one will be selected.
    tag nameLocates elements whose tag name matches the search value
    xpathLocates elements matching an XPath expression
    # 사용 예시
    driver = webdriver.Chrome()
    driver.find_element(By.CLASS_NAME, "information")
    driver.find_element(By.CSS_SELECTOR, "#fname")
    driver.find_element(By.ID, "lname")
    driver.find_element(By.NAME, "newsletter")
    driver.find_element(By.LINK_TEXT, "Selenium Official Page")
    driver.find_element(By.PARTIAL_LINK_TEXT, "Official Page")
    driver.find_element(By.TAG_NAME, "a")
    driver.find_element(By.XPATH, "//input[@value='f']")
    #locator의 경우 By class에 각각 문자열로 mapping되어 있기 때문에 그냥 문자열로 적어도 됨
    """The By implementation."""
    class By:
        """Set of supported locator strategies."""
        ID = "id"
        XPATH = "xpath"
        LINK_TEXT = "link text"
        PARTIAL_LINK_TEXT = "partial link text"
        NAME = "name"
        TAG_NAME = "tag name"
        CLASS_NAME = "class name"
        CSS_SELECTOR = "css selector"
  • 상호작용 (click, text field 입력/비우기, list element select)

🍃Selenium 테스트 코드

  • Selenium Grid로 테스트

    from selenium import webdriver
    import time
    
    print("Test Execution Started")
    
    # ssl 에러와 인증 에러를 무시하도록 설정
    options = webdriver.ChromeOptions()
    options.add_argument('--ignore-ssl-errors=yes')
    options.add_argument('--ignore-certificate-errors')
    
    # 아까 만들어둔 도커 컨테이너(Selenium Grid)에서 동작하는 원격 webdriver 생성
    driver = webdriver.Remote(
        command_executor='http://localhost:4444/wd/hub',
        options=options
    )
    
    # maximize the window size
    driver.maximize_window()
    time.sleep(10)
    
    # navigate to the notes app
    driver.get("https://notes.prgms-fullcycle.com")
    time.sleep(10)
    
    # click on the Get started for free button
    driver.find_element("link text", "무료로 시작하기").click()
    time.sleep(10)
    
    # close the browser
    s = input("Done: ")
    
    driver.close()
    driver.quit()
    
    print("Test Execution Successfully Completed!")

    코드를 실행하면 http://localhost:4444/ui/#/sessions에서 녹화 아이콘 클릭해서 확인 가능 (비밀번호: secret)

  • local에서 테스트 (login, logout 정도 추가해봄)

    from selenium import webdriver
    import time
    
    print("Test Execution Started")
    
    options = webdriver.ChromeOptions()
    options.add_argument("--ignore-ssl-errors=yes")
    options.add_argument("--ignore-certificate-errors")
    
    driver = webdriver.Chrome()  # test on local
    
    # maximize the window size
    driver.maximize_window()
    time.sleep(2)
    
    # navigate to the notes app
    driver.get("http://localhost:30030/")
    time.sleep(2)
    
    # click on the Get started for free button
    driver.find_element("link text", "무료로 시작하기").click()
    time.sleep(1)
    
    # login
    driver.find_element("name", "email").send_keys("test@gmail.com")
    driver.find_element("name", "password").send_keys("1234")
    time.sleep(1)
    # driver.find_element("tag name", "button").click()   # 아래와 같은 표현
    driver.find_element("xpath", "//button[contains(., '로그인')]").click()
    time.sleep(2)
    
    # logout
    # driver.find_element(
    #     "css selector", "#root > div > div.side-bar > button:nth-child(2)"
    # ).click()   # 아래와 같은 표현
    driver.find_element("xpath", "//button[contains(., '로그아웃')]").click()
    
    # close the browser
    s = input("Done: ")
    
    driver.close()
    driver.quit()
    
    print("Test Execution Successfully Completed!")

※ 지금은 눈으로 보려고 time.sleep을 사용 → driver.implicitly_wait(sec)를 사용하면 요소가 렌더링되는 즉시 테스트가 실행된다.

profile
이것저것 관심 많은 개발자👩‍💻

0개의 댓글