Selenium 웹드라이버를 사용하면 웹 페이지의 요소와 그 안의 텍스트를 손쉽게 찾을 수 있습니다. 먼저 id, classname, css 등 다양한 로케이터(locator) 중 하나를 활용해 대상 요소를 식별해야 합니다. 그다음 text 메서드를 사용하면 해당 요소의 텍스트 내용을 가져올 수 있습니다.
문법
s = driver.find_element_by_css_selector("h4").text여기서 driver는 웹드라이버 객체입니다. find_element_by_css_selector 메서드는 CSS 로케이터 방식으로 요소를 식별하며, 로케이터 값이 인수로 전달됩니다. 마지막으로 text 메서드를 통해 해당 요소의 텍스트 콘텐츠를 얻습니다.
텍스트 콘텐츠를 포함하는 요소의 HTML 예시를 살펴보겠습니다. 실행 결과는 You are browsing the best resource for Online Education입니다.
예제
코드 구현 예시는 다음과 같습니다.
from selenium import webdriver
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe"
# 암시적 대기(implicit wait) 적용
driver.implicitly_wait(0.5)
driver.get("https://www.tutorialspoint.com/index.htm")
# 요소를 식별하고 텍스트 가져오기
s = driver.find_element_by_css_selector("h4").text
print("The text is: " + s)
출력 결과
위 코드를 실행하면 지정한 h4 요소의 텍스트가 콘솔에 출력되며, 결과는 다음과 같습니다.
The text is: You are browsing the best resource for Online Education
참고: Selenium 4 이상에서의 변경 사항
Selenium 4부터는 find_element_by_css_selector 같은 개별 로케이터 메서드가 제거되었습니다. 최신 버전에서는 By 모듈을 함께 사용하는 아래 방식을 권장합니다.
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.get("https://www.tutorialspoint.com/index.htm")
s = driver.find_element(By.CSS_SELECTOR, "h4").text
print("The text is: " + s)
이처럼 Selenium과 Python을 조합하면 원하는 요소를 정확히 식별하고, 그 텍스트 값을 간단하게 추출할 수 있습니다. 크롤링 자동화나 UI 테스트 작성 시 매우 유용하게 활용됩니다.