feat(ssulbox): 업장 검색을 ADO2 방식으로 전환하고 URL 해석을 워커로 이관
This commit is contained in:
1 parent
50dc7af5bc
commit
459099998e
5 files changed
+296
-198
No files matched your search
@@ -1,26 +1,27 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""네이버 지도 업장 검색 (키 불필요, Playwright).
|
||||
"""네이버 지도 업장 정보 조회 (Playwright).
|
||||
|
||||
`map.naver.com/p/search/{query}` 의 검색 리스트 iframe(`pcmap.place.naver.com/place/list`)
|
||||
안에 있는 `__APOLLO_STATE__` 를 파싱해, 동명 업장들을 주소로 구분한 후보 목록을 만든다.
|
||||
각 후보는 `place_url`(map.naver.com/p/entry/place/{id})을 가지므로, 사용자가 하나를 고르면
|
||||
그 URL 을 그대로 생성 파이프라인(generator/naver.py)에 넘겨 정확히 그 가게를 크롤링한다.
|
||||
두 가지를 한다:
|
||||
1. `resolve_place_url` — 업장명(+주소) → place URL.
|
||||
**castad `NvMapPwScraper.get_place_id_url` 을 재사용**한다(ADO2 자동완성과 동일 경로).
|
||||
2. `fetch_place_detail` — place URL → 업장명·주소.
|
||||
생성 시 store_name/region 을 채우는 데 쓴다. place 상세의 `__APOLLO_STATE__`
|
||||
안 `PlaceDetailBase:{id}` 를 파싱한다.
|
||||
|
||||
**castad `/search/accommodation` 으로 대체할 수 없다.** 그쪽은 네이버 *검색 API* 라
|
||||
`title`/`address`/`roadAddress` 만 주고 `place_url` 이 없는데, generator 가 place 페이지를
|
||||
크롤링하므로 URL 이 반드시 필요하다. (castad `NvMapPwScraper` 는 후보=NAVER API,
|
||||
place_id 해석=Playwright 로 2단계를 밟지만 여기서는 지도만으로 한 번에 얻는다.)
|
||||
**후보 목록 검색은 여기 없다.** 예전에는 지도 검색 iframe 을 크롤링해 후보를
|
||||
받았지만 **17초**가 걸려, ADO2 와 동일하게 네이버 검색 API(`/search/accommodation`,
|
||||
~0.2초)로 자동완성하고 place URL 은 제출 시 1건만 해석하도록 바꿨다(2026-07-31).
|
||||
"""
|
||||
import asyncio
|
||||
import json
|
||||
import sys
|
||||
from urllib.parse import quote
|
||||
|
||||
from playwright.async_api import async_playwright
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
# URL 정규화(단축링크 해석·place_id 추출)는 castad 크롤러 것을 그대로 쓴다.
|
||||
# 무거운 scrap() 은 쓰지 않는다 — fetch_place_detail docstring 참조.
|
||||
from app.utils.nvMapPwScraper import NvMapPwScraper
|
||||
from app.utils.nvMapScraper import NvMapScraper, URLNotFoundException
|
||||
|
||||
logger = get_logger("ssulbox")
|
||||
@@ -66,87 +67,42 @@ def _extract_apollo_state(html: str) -> dict | None:
|
||||
return None
|
||||
|
||||
|
||||
def _candidates_from_state(state: dict, limit: int) -> list[dict]:
|
||||
out: list[dict] = []
|
||||
for key, obj in state.items():
|
||||
if not key.startswith("PlaceListBusinessesItem:"):
|
||||
continue
|
||||
if not isinstance(obj, dict):
|
||||
continue
|
||||
name = obj.get("name")
|
||||
pid = obj.get("id")
|
||||
if not (name and pid and str(pid).isdigit()):
|
||||
continue
|
||||
out.append(
|
||||
{
|
||||
"title": name,
|
||||
"category": obj.get("category") or "",
|
||||
# 표시용 주소는 '서울 성동구 금호동3가' 같은 commonAddress 를 우선(동명 구분에 최적)
|
||||
"address": obj.get("commonAddress") or obj.get("fullAddress") or "",
|
||||
"roadAddress": obj.get("fullAddress") or obj.get("roadAddress") or "",
|
||||
"place_url": f"https://map.naver.com/p/entry/place/{pid}",
|
||||
}
|
||||
)
|
||||
if len(out) >= limit:
|
||||
break
|
||||
return out
|
||||
async def resolve_place_url(
|
||||
title: str, address: str = "", road_address: str = ""
|
||||
) -> str | None:
|
||||
"""업장명(+주소)으로 네이버 지도 place URL 을 해석한다.
|
||||
|
||||
**castad `NvMapPwScraper.get_place_id_url` 을 그대로 재사용한다** — ADO2 자동완성이
|
||||
쓰는 바로 그 경로다(`app/home` 의 `_autocomplete_logic`). allSearch API 응답을
|
||||
캡처해 이름·주소 유사도로 후보를 고르고, 실패하면 정제주소 → 업체명 단독 →
|
||||
컨텍스트 재생성 순으로 3단 재시도한다.
|
||||
|
||||
async def _search(query: str, limit: int) -> list[dict]:
|
||||
async with async_playwright() as p:
|
||||
browser = await p.chromium.launch(
|
||||
headless=True,
|
||||
args=["--disable-blink-features=AutomationControlled", "--no-sandbox"],
|
||||
썰박스 자체 지도 크롤링(`search_places`)을 쓰지 않는 이유: 그쪽은 후보 목록을
|
||||
받으려고 iframe 렌더를 기다려 **17초**가 걸린다. ADO2 는 후보 탐색을 네이버
|
||||
검색 API(0.2초)로 하고 여기서는 확정된 1건만 해석하므로 훨씬 빠르고,
|
||||
안티봇 차단 대응까지 이미 들어 있다.
|
||||
|
||||
실패하면 None. 호출부는 사용자가 링크를 직접 붙여넣는 우회 경로를 남겨둔다.
|
||||
"""
|
||||
title = (title or "").strip()
|
||||
if not title:
|
||||
return None
|
||||
try:
|
||||
selected = {
|
||||
"title": title,
|
||||
"address": address or "",
|
||||
"roadAddress": road_address or address or "",
|
||||
}
|
||||
async with NvMapPwScraper() as scraper:
|
||||
url = await scraper.get_place_id_url(selected)
|
||||
logger.info(f"[resolve_place_url] {title!r} → {url}")
|
||||
return url
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f"[resolve_place_url] FAILED {title!r} - {type(e).__name__}: {e}",
|
||||
exc_info=True,
|
||||
)
|
||||
try:
|
||||
ctx = await browser.new_context(
|
||||
user_agent=DESKTOP_UA, locale="ko-KR", timezone_id="Asia/Seoul",
|
||||
viewport={"width": 1280, "height": 800},
|
||||
extra_http_headers={"Accept-Language": "ko-KR,ko;q=0.9"},
|
||||
)
|
||||
page = await ctx.new_page()
|
||||
await page.goto(
|
||||
f"https://map.naver.com/p/search/{quote(query)}",
|
||||
wait_until="domcontentloaded", timeout=40000,
|
||||
)
|
||||
# 검색 리스트 iframe 이 뜰 때까지 대기(최대 ~12초)
|
||||
frame = None
|
||||
for _ in range(24):
|
||||
for f in page.frames:
|
||||
if "pcmap.place.naver.com/place/list" in f.url:
|
||||
frame = f
|
||||
break
|
||||
if frame:
|
||||
break
|
||||
# 단일 결과면 곧바로 place 상세로 리다이렉트됨 → 후보 1개로 처리.
|
||||
# 이때도 **주소를 반드시 채운다**. 예전에는 빈 문자열을 돌려줬는데,
|
||||
# 그러면 프론트가 주소를 못 보내고 지역(region)이 NULL 이 되어
|
||||
# 그 콘텐츠가 통합 목록의 지역 필터에서 영구 제외된다.
|
||||
if "/place/" in page.url and "/search/" not in page.url:
|
||||
detail = await _extract_detail_from_page(page)
|
||||
if detail:
|
||||
detail["place_url"] = page.url
|
||||
return [detail]
|
||||
# 상세 파싱까지 실패하면 최소 정보라도 준다(생성은 가능해야 한다)
|
||||
return [{"title": query, "category": "", "address": "",
|
||||
"roadAddress": "", "place_url": page.url}]
|
||||
await page.wait_for_timeout(500)
|
||||
if not frame:
|
||||
return []
|
||||
# apollo state 가 채워질 시간을 조금 더 준다
|
||||
html = await frame.content()
|
||||
state = _extract_apollo_state(html)
|
||||
for _ in range(6):
|
||||
if state and any(k.startswith("PlaceListBusinessesItem:") for k in state):
|
||||
break
|
||||
await page.wait_for_timeout(600)
|
||||
html = await frame.content()
|
||||
state = _extract_apollo_state(html)
|
||||
if not state:
|
||||
return []
|
||||
return _candidates_from_state(state, limit)
|
||||
finally:
|
||||
await browser.close()
|
||||
return None
|
||||
|
||||
|
||||
def _detail_from_state(state: dict) -> dict | None:
|
||||
@@ -284,44 +240,3 @@ async def fetch_place_detail(
|
||||
return None
|
||||
|
||||
|
||||
def _search_blocking(query: str, limit: int) -> list[dict]:
|
||||
"""별도 스레드에서 자체 이벤트 루프로 Playwright 실행.
|
||||
|
||||
Windows 의 웹서버 루프(Selector)는 서브프로세스를 못 띄워 Playwright 가 즉시 실패한다.
|
||||
→ 이 함수는 워커 스레드에서 Proactor 루프(윈도우) 를 새로 만들어 그 위에서 돌린다.
|
||||
"""
|
||||
if sys.platform == "win32":
|
||||
loop = asyncio.ProactorEventLoop()
|
||||
else:
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
return loop.run_until_complete(_search(query, limit))
|
||||
finally:
|
||||
loop.close()
|
||||
|
||||
|
||||
async def search_places(query: str, limit: int = 8, timeout: float = 35.0) -> list[dict]:
|
||||
"""업장명으로 네이버 지도 후보 목록을 반환. 실패/타임아웃이면 빈 리스트.
|
||||
|
||||
실패해도 예외를 올리지 않는다 — 사용자에게는 네이버 링크를 직접 붙여넣는
|
||||
우회 경로가 있으므로 흐름을 막지 않는다. 다만 원본은 예외를 통째로 삼켜
|
||||
디버깅이 불가능했으므로 로그는 남긴다.
|
||||
"""
|
||||
query = (query or "").strip()
|
||||
if len(query) < 2:
|
||||
return []
|
||||
try:
|
||||
results = await asyncio.wait_for(
|
||||
asyncio.to_thread(_search_blocking, query, limit), timeout=timeout
|
||||
)
|
||||
logger.info(f"[search_places] query='{query}' → {len(results)}건")
|
||||
return results
|
||||
except asyncio.TimeoutError:
|
||||
logger.warning(f"[search_places] TIMEOUT ({timeout}s) query='{query}'")
|
||||
return []
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f"[search_places] FAILED query='{query}' - {type(e).__name__}: {e}",
|
||||
exc_info=True,
|
||||
)
|
||||
return []
|
||||
Reference in new issue
Block a user