15장: Playwright가 익스텐션을 구동하기
2부(Playwright)와 3부(익스텐션+LLM)를 각각 따로 만들었습니다. 이 장에서 하나로 잇습니다 — 로그인과 대기열은 Playwright가 직접 하고, 좌석 선택은 실제 팝업을 열어 익스텐션이 LLM으로 판단하게 합니다.
전체 스크립트
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
ext_path = "./ext"
context = p.chromium.launch_persistent_context(
"./udata",
headless=False,
args=[
"--headless=new", # 18장에서 다시 다룹니다
f"--disable-extensions-except={ext_path}",
f"--load-extension={ext_path}",
],
)
sw = next(iter(context.service_workers), None)
if sw is None:
sw = context.wait_for_event("serviceworker", timeout=10000)
extension_id = sw.url.split("/")[2]
page = context.new_page()
page.goto("http://localhost:4100")
# 3장: 로그인
page.fill("#name", "홍길동")
page.fill("#phone", "010-1234-5678")
page.click("#login")
page.wait_for_selector("#enter", state="visible")
# 4장: 대기열
position = float("inf")
while position > 0:
page.click("#enter")
position = int(page.locator("#qpos").inner_text())
page.wait_for_selector("#seatmap-area", state="visible")
print("queue cleared, seatmap visible")
# 8장: 실제 팝업을 별도 페이지로 열어 그대로 조작한다 (7장의 격리된 world 함정을 피하는 방법)
popup = context.new_page()
popup.goto(f"chrome-extension://{extension_id}/popup.html")
popup.fill("#pref", "3루측 그늘, 앞뒤 여유 있는 자리")
popup.click("#go")
popup.wait_for_timeout(500)
print("popup result:", popup.locator("#out").inner_text())
print("final reservation status on the ticket page:", page.locator("#status").inner_text())
context.close()실행 확인
$ python pw_full.py
extension id: iadoncnhoibfgfimpeklloaicnhndaph
queue cleared, seatmap visible
popup result: {
"chosen": {
"col": 4,
"reason": "3루측 그늘, 앞뒤 여유 있는 자리",
"row": 0
},
"ok": true
}
final reservation status on the ticket page: 예매 완료: 0행 4열한 프로세스 안에서 Playwright가 로그인 폼을 채우고, 대기열을 뚫고, 실제 익스텐션 팝업을 열어 선호도를 입력하고, 그 팝업이 content script → service worker → LLM(모크) → content script로 이어지는 전체 왕복을 실행해 좌석을 클릭했고, 원래 예매 페이지에 `예매 완료: 0행 4열`이 떴습니다(모크 LLM이 매번 후보 중 하나를 무작위로 고르므로, 실행마다 좌표는 달라질 수 있습니다 — 13장 참고). 이게 이 책이 처음부터 짓고 있던 하이브리드 파이프라인입니다 — 규칙이 명확한 부분은 Playwright가, 판단이 필요한 부분은 익스텐션과 LLM이 처리했습니다.
요약
Playwright 한 스크립트 안에서 일반 페이지 자동화(로그인·대기열)와 익스텐션 팝업 조작을 순서대로 이었습니다.
`page.evaluate()`로 content script 함수를 직접 부르는 대신(7장의 함정), 실제 팝업 페이지를 열어 버튼을 누르는 방식으로 정확한 통신 경로를 재현했습니다.
전체 파이프라인을 실제로 끝까지 실행해, 로그인부터 최종 예매 완료 메시지까지 하나의 로그로 확인했습니다.