본문 바로가기
Python/Selenium

selenium.webdriver.find_elements_by_class_name로 요소 리스트 얻기

by PySun 2025. 1. 22.
반응형

Selenium WebDriver: find_elements_by_class_name로 요소 리스트 얻기

웹 스크래핑 및 자동화 테스트의 강력한 도구인 Selenium을 사용하면 웹 페이지의 다양한 요소를 쉽고 빠르게 조작할 수 있습니다. 이 포스팅에서는 find_elements_by_class_name 메서드를 활용하여 HTML 요소 리스트를 효율적으로 얻는 방법에 대해 알아보겠습니다.

find_elements_by_class_name 메서드 소개

find_elements_by_class_name 메서드는 웹 페이지에서 지정된 클래스 이름을 가진 모든 요소를 찾아서 리스트 형태로 반환합니다. 이를 통해 동일한 특성을 가진 여러 요소를 간편하게 조작할 수 있습니다. 웹 페이지의 요소를 탐색하고 자동화하는 데 필수적인 도구입니다.

함수 시그니처

driver.find_elements_by_class_name(class_name)

매개변수:

  • class_name: 찾고자 하는 요소의 클래스 이름을 문자열로 지정합니다.

반환 값:

  • 지정된 클래스 이름을 가진 요소들의 리스트를 반환합니다.

사용 예제

기본 예제

여기에서는 find_elements_by_class_name 메서드를 사용하여 클래스 이름이 "item"인 모든 요소를 찾는 예제를 소개합니다.

from selenium import webdriver

# 웹 드라이버 설정
driver = webdriver.Chrome()

# 웹 페이지 열기
driver.get('https://example.com')

# 클래스 이름으로 요소 리스트 얻기
elements = driver.find_elements_by_class_name('item')

# 결과 출력
for element in elements:
    print(element.text)

# 드라이버 종료
driver.quit()

다양한 클래스 이름 예제

특정 클래스를 가진 여러 타입의 요소들을 찾아보는 예제를 살펴보겠습니다.

from selenium import webdriver

# 웹 드라이버 설정
driver = webdriver.Chrome()

# 웹 페이지 열기
driver.get('https://example.com')

# 여러 클래스 이름으로 요소 리스트 얻기
class_names = ['header', 'footer', 'content']
for class_name in class_names:
    elements = driver.find_elements_by_class_name(class_name)
    print(f"Elements with class '{class_name}':")
    for element in elements:
        print(element.text)

# 드라이버 종료
driver.quit()

결론

find_elements_by_class_name 메서드는 웹 페이지에서 동일한 클래스를 가진 요소들을 손쉽게 찾고 조작할 수 있는 강력한 도구입니다. 효율적인 자동화 작업을 위해 이 메서드를 활용하여 여러 요소를 동시에 다루어 보세요!

  • 웹 데이터를 수집하거나 테스트 자동화를 할 때 find_elements_by_class_name를 활용해 보세요!
  • 더욱 간편하고 효율적인 웹 자동화를 위해 다양한 클래스 이름을 사용해 보세요!
반응형