🧪 Selenium · 레슨 2 / 6

Selenium 로케이터와 요소 조작 — By 전략, CSS·XPath, 상대 로케이터, 폼·Select·프레임·창

Selenium의 8가지 By 로케이터 전략과 선택 기준, 실무에서 쓰는 CSS 셀렉터와 XPath 패턴, 상대 로케이터, find_element와 find_elements의 차이, 입력·클릭·Select·체크박스·파일 업로드, ActionChains, iframe·새 창·알림창 전환을 배웁니다.

⏱ 약 5분🗓 2026-11-13 업데이트🏷 Selenium 4.x 기준

이 레슨에서 배우는 것

  • 상황에 맞는 By 전략과 안정적인 셀렉터 고르기
  • 폼 요소와 마우스·키보드 동작 다루기
  • iframe·새 창·알림창으로 컨텍스트 전환하기

By 전략

전략 (Python)Java예평가
By.IDBy.id"my-text-id"고유하고 고정된 id라면 최선
By.NAMEBy.name"my-password"폼 필드에 좋음
By.CSS_SELECTORBy.cssSelector"[data-test=submit]"가장 범용. 기본 선택지
By.XPATHBy.xpath"//button[text()='Submit']"텍스트·부모 방향 탐색이 필요할 때
By.LINK_TEXT / PARTIAL_LINK_TEXTBy.linkText"Return to index"링크 전용
By.CLASS_NAME / By.TAG_NAMEBy.className"form-control"대개 여러 개가 일치. 범위를 좁힌 뒤 사용

가장 안정적인 것은 개발팀과 합의한 테스트 전용 속성(data-test, data-testid)입니다. 화면 구조(div > div:nth-child(3) > span)나 자동 생성 클래스(css-1x2y3z)에 기대는 셀렉터는 작은 UI 변경에도 깨집니다.

CSS와 XPath 패턴

text
CSS
  [data-test="login"]              속성 일치
  input[name^="user"]              속성이 user로 시작
  a[href*="checkout"]              속성에 checkout 포함
  form#login button[type=submit]   자손
  ul.menu > li:first-child         자식, 첫 번째

XPath
  //button[normalize-space()='저장']              텍스트가 정확히 '저장'인 버튼
  //label[text()='이메일']/following-sibling::input   라벨 옆 입력란
  //td[text()='홍길동']/ancestor::tr//button      특정 행 안의 버튼 (부모 방향)
  (//div[@class='card'])[2]                       두 번째 카드

CSS는 읽기 쉽고 빠르지만 텍스트로 찾거나 부모 쪽으로 올라갈 수 없습니다. 그 두 경우에만 XPath를 쓰는 것이 일반적입니다. 브라우저 개발자 도구 콘솔에서 $$('css'), $x('xpath')로 셀렉터를 미리 시험해 보세요.

find_element와 find_elements

python
from selenium.webdriver.common.by import By

el = driver.find_element(By.ID, "my-text-id")       # 첫 번째 일치. 없으면 NoSuchElementException
items = driver.find_elements(By.CSS_SELECTOR, "li") # 리스트. 없으면 빈 리스트 (예외 없음)

# 요소 안에서 찾기 (범위 좁히기)
form = driver.find_element(By.TAG_NAME, "form")
inputs = form.find_elements(By.TAG_NAME, "input")

# 요소 정보
el.text, el.tag_name, el.get_attribute("value"), el.get_dom_attribute("name")
el.is_displayed(), el.is_enabled(), el.is_selected()
💡
존재 여부 확인

"요소가 없어야 한다"를 확인할 때는 예외를 잡기보다 len(driver.find_elements(...)) == 0이 간단합니다. 단, 사라지는 데 시간이 걸린다면 3강의 명시적 대기(invisibility_of_element_located)를 쓰세요.

상대 로케이터

Selenium 4에서 추가된 기능으로, 다른 요소와의 화면상 위치로 요소를 찾습니다. 속성이 부족한 레거시 화면에서 유용합니다.

python
from selenium.webdriver.support.relative_locator import locate_with

password_label = driver.find_element(By.XPATH, "//label[contains(., 'Password')]")
password = driver.find_element(locate_with(By.TAG_NAME, "input").below(password_label))

cancel = driver.find_element(locate_with(By.TAG_NAME, "button").to_left_of({By.ID: "submit"}))

above, below, to_left_of, to_right_of, near를 쓸 수 있습니다. 화면 크기에 따라 배치가 바뀌는 반응형 화면에서는 결과가 달라질 수 있으니 고정 레이아웃에서만 쓰세요.

폼 조작

python
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select

text = driver.find_element(By.NAME, "my-text")
text.clear()
text.send_keys("홍길동")
text.send_keys(Keys.CONTROL, "a")     # 키 조합 (macOS는 Keys.COMMAND)

driver.find_element(By.NAME, "my-textarea").send_keys("여러 줄\n입력")

# 드롭다운
select = Select(driver.find_element(By.NAME, "my-select"))
select.select_by_visible_text("Two")   # 또는 select_by_value("2"), select_by_index(1)
assert select.first_selected_option.text == "Two"

# 체크박스·라디오
checkbox = driver.find_element(By.ID, "my-check-2")
if not checkbox.is_selected():
    checkbox.click()

# 파일 업로드: input[type=file]에 절대 경로를 send_keys
driver.find_element(By.NAME, "my-file").send_keys("/abs/path/report.pdf")

# 폼 제출
driver.find_element(By.CSS_SELECTOR, "button[type=submit]").click()

마우스·키보드 동작

python
from selenium.webdriver import ActionChains

menu = driver.find_element(By.ID, "menu")
item = driver.find_element(By.ID, "menu-settings")
ActionChains(driver).move_to_element(menu).click(item).perform()      # 호버 메뉴

ActionChains(driver).drag_and_drop(source_el, target_el).perform()
ActionChains(driver).double_click(el).context_click(el).perform()
ActionChains(driver).scroll_to_element(footer).perform()

perform()을 호출해야 쌓아 둔 동작이 실행됩니다.

iframe·창·알림창 전환

WebDriver는 한 번에 하나의 브라우징 컨텍스트만 바라봅니다. iframe 안의 요소나 새 창의 요소를 찾으려면 먼저 전환해야 하며, 전환하지 않으면 요소가 있어도 NoSuchElementException이 납니다.

python
# iframe
driver.switch_to.frame(driver.find_element(By.CSS_SELECTOR, "iframe#payment"))
driver.find_element(By.NAME, "card").send_keys("4242...")
driver.switch_to.default_content()          # 원래 문서로 복귀

# 새 창·탭
original = driver.current_window_handle
driver.find_element(By.LINK_TEXT, "약관 보기").click()
for handle in driver.window_handles:
    if handle != original:
        driver.switch_to.window(handle)
assert "이용약관" in driver.title
driver.close()                              # 새 창 닫기
driver.switch_to.window(original)

driver.switch_to.new_window("tab")          # 새 탭을 직접 열기

# alert / confirm / prompt
alert = driver.switch_to.alert
assert alert.text == "삭제하시겠습니까?"
alert.accept()                              # 또는 dismiss(), send_keys("입력")

정리