Selenium 웹드라이버를 활용한 요소 탐색 및 제어 방법

1. Selenium 개요 및 설치

Selenium은 웹 브라우저를 자동으로 제어할 수 있는 도구로, 주로 웹 애플리케이션 테스트에 사용됩니다. 사용자가 미리 정의한 명령에 따라 브라우저가 페이지를 로드하고, 데이터를 수집하며, 특정 동작이 발생했는지 확인할 수 있습니다. Selenium 자체는 브라우저 기능을 포함하지 않으며, Chrome, Edge, Firefox 등의 실제 브라우저와 연동하여 동작합니다.

설치는 pip를 통해 간단히 진행할 수 있습니다.

pip install selenium -i https://pypi.tuna.tsinghua.edu.cn/simple

주의사항: Selenium이 브라우저를 제어하려면 드라이버가 필요합니다. Selenium 4.6.0 이상 버전에서는 드라이버를 자동으로 다운로드하지만, 그 이전 버전은 수동으로 다운로드해야 합니다.

첫 번째 Selenium 프로그램

from selenium.webdriver import Edge

driver = Edge()
driver.get('https://www.google.com/')
html_source = driver.page_source
print(html_source)
driver.quit()

2. 브라우저 창 제어

2.1 창 최대화

maximize_window() 메서드를 사용하여 브라우저 창을 전체 화면으로 확장합니다.

from selenium.webdriver import Edge
import time

driver = Edge()
driver.get('https://www.google.com/')
driver.maximize_window()
time.sleep(5)
driver.quit()

2.2 창 크기 설정

set_window_size(width, height)를 사용하여 브라우저의 너비와 높이를 지정할 수 있습니다.

2.3 앞으로/뒤로 이동

  • 앞으로: driver.forward()
  • 뒤로: driver.back()

앞/뒤 이동 예제

from selenium.webdriver import Edge
import time

driver = Edge()
driver.get('https://www.google.com/')
time.sleep(3)

driver.get('https://www.github.com/')
time.sleep(3)

driver.back()  # Google로 이동
time.sleep(5)

driver.forward()  # GitHub로 다시 이동
time.sleep(5)

driver.quit()

3. 요소 찾기

자동화의 핵심은 대상 요소를 정확히 식별하는 것입니다. Selenium은 다양한 속성(ID, 이름, 클래스, 태그, XPath, CSS 선택자 등)을 기반으로 요소를 찾을 수 있습니다.

3.1 요소 찾기 메서드

  • find_element(type, value): 조건에 맞는 첫 번째 요소 반환
  • find_elements(type, value): 조건에 맞는 모든 요소를 리스트로 반환

type 매개변수에 사용할 수 있는 주요 로케이터:

  • By.ID
  • By.NAME
  • By.CLASS_NAME
  • By.TAG_NAME
  • By.LINK_TEXT
  • By.PARTIAL_LINK_TEXT
  • By.XPATH
  • By.CSS_SELECTOR

3.2 요소 조작

  • click(): 요소 클릭
  • send_keys("텍스트"): 입력 필드에 텍스트 입력
  • clear(): 입력 필드 내용 지우기

3.3 실습 예제

from selenium.webdriver.common.by import By
from selenium.webdriver import Edge
import time

driver = Edge()
driver.get('https://www.google.com/')
time.sleep(3)

search_box = driver.find_element(By.NAME, "q")
search_box.send_keys("Selenium")
time.sleep(1)

search_button = driver.find_element(By.NAME, "btnK")
search_button.click()
time.sleep(3)

driver.quit()

4. 드롭다운 메뉴 처리

웹 페이지에서 드롭다운 메뉴는 일반적으로 <select> 태그 또는 CSS 기반 드롭다운으로 구현됩니다. Selenium을 사용해 항목을 선택할 수 있습니다.

HTML 예제

<html>
<body>
<div class="dropdown">
    <a class="dropdown-toggle" data-toggle="dropdown" href="#">메뉴1</a>
    <ul class="dropdown-menu">
        <li><a href="https://example.com/action">Action</a></li>
        <li><a href="#">Another action</a></li>
    </ul>
</div>
</body>
</html>

드롭다운 항목 클릭 예제:

from selenium.webdriver.common.by import By
from selenium.webdriver import Edge
import time

driver = Edge()
driver.get('file:///path/to/menu.html')
time.sleep(3)

driver.find_element(By.CLASS_NAME, "dropdown-toggle").click()
time.sleep(1)

driver.find_element(By.LINK_TEXT, 'Action').click()
time.sleep(3)

driver.quit()

5. iframe 내부 요소 접근

웹 페이지 내 iframe이 포함된 경우, 요소를 직접 찾을 수 없을 수 있습니다. 이때는 switch_to.frame() 메서드를 사용해 iframe으로 접근 컨텍스트를 전환해야 합니다.

중첩 iframe 예제

inner.html:

<html>
<body>
    <iframe id="f2" src="https://example.com"></iframe>
</body>
</html>

outer.html:

<html>
<body>
    <iframe id="f1" src="inner.html"></iframe>
</body>
</html>

iframe 전환 및 요소 조작 예제:

from selenium.webdriver.common.by import By
from selenium.webdriver import Edge
import time

driver = Edge()
driver.get('file:///path/to/outer.html')
time.sleep(3)

driver.switch_to.frame('f1')
driver.switch_to.frame('f2')

search_input = driver.find_element(By.ID, 'search-input')
search_input.send_keys('검색어')
time.sleep(2)

search_btn = driver.find_element(By.ID, 'search-button')
search_btn.click()
time.sleep(3)

driver.quit()

6. 학습 개념 요약

다음은 Selenium 요소 탐색 및 제어의 주요 개념을 정리한 것입니다.

태그: selenium webdriver element-location iframe dropdown-menu

6월 14일 22:51에 게시됨