React로 만들어진 웹페이지는 데이터를 서버에서 바로 가져오는 게 아니라,
브라우저에서 JavaScript로 렌더링되는 경우가 많습니다.
이럴 때 BeautifulSoup처럼 단순 HTML 파싱으로는 안 되고,
Selenium으로 실제 브라우저를 띄워 렌더링된 데이터를 읽어야 합니다.
---
🔹 예제 시나리오
React 기반 페이지(예: 상품 목록 페이지)가 있다고 할 때,
다음 데이터를 자동으로 수집합니다.
> 예: https://example-react-shop.com/products
상품 이름
가격
상세 링크
---
🔹 Python + Selenium 예제 코드
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
import time
# --- 1️⃣ Headless(화면 없이) 실행 설정 ---
options = Options()
options.add_argument("--headless") # 브라우저 창 안 띄움
options.add_argument("--no-sandbox")
options.add_argument("--disable-dev-shm-usage")
# --- 2️⃣ 크롬 드라이버 실행 ---
driver = webdriver.Chrome(options=options)
# --- 3️⃣ React 페이지 접속 ---
url = "https://example-react-shop.com/products"
driver.get(url)
# --- 4️⃣ JavaScript 로딩 대기 ---
time.sleep(5) # 페이지 렌더링 대기 (WebDriverWait으로 대체 가능)
# --- 5️⃣ 상품 정보 수집 ---
items = driver.find_elements(By.CSS_SELECTOR, ".product-card")
for item in items:
name = item.find_element(By.CSS_SELECTOR, ".product-name").text
price = item.find_element(By.CSS_SELECTOR, ".product-price").text
link = item.find_element(By.TAG_NAME, "a").get_attribute("href")
print(f"상품명: {name}, 가격: {price}, 링크: {link}")
# --- 6️⃣ 브라우저 종료 ---
driver.quit()
---
🔹 React 페이지 특징 처리 포인트
상황 해결 방법
페이지 로딩이 느림 time.sleep() 대신 WebDriverWait 사용
무한 스크롤 driver.execute_script("window.scrollTo(0, document.body.scrollHeight)") 반복
동적 버튼 클릭 driver.find_element(By.XPATH, "//button[text()='더 보기']").click()
로그인 필요 아이디/비밀번호 입력 후 .click() 실행
---
🔹 예: 무한 스크롤 데이터 수집
# 무한 스크롤
import time
last_height = driver.execute_script("return document.body.scrollHeight")
while True:
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(2)
new_height = driver.execute_script("return document.body.scrollHeight")
if new_height == last_height:
break
last_height = new_height
---
🔹 출력 예시
상품명: MacBook Pro 14"
가격: ₩2,490,000
링크: https://example-react-shop.com/products/macbook-pro-14
상품명: iPhone 15 Pro
가격: ₩1,550,000
링크: https://example-react-shop.com/products/iphone-15-pro
---
🔹 정리
항목 내용
언어 Python
도구 Selenium + ChromeDriver
용도 React 렌더링된 데이터 수집
특징 실제 브라우저 렌더링 기반, 동적 컨텐츠 수집 가능
대안 Puppeteer(Node.js), Playwright(Python/JS) — 더 빠르고 안정적
'skill > check' 카테고리의 다른 글
| Junit 기반 백엔드 테스트 스위트 (0) | 2025.10.15 |
|---|---|
| 테스트 스위트(Test Suite) (0) | 2025.10.14 |
| 셀레니움(Selenium) 단점 (0) | 2025.10.14 |
| 셀레니움(Selenium) (0) | 2025.10.14 |