네이버 크롤링 우회 코드 추가

This commit is contained in:
skkim committed 2026-06-29 10:36:53 +09:00
1 parent b908408b4a
commit 8415e1c3a7
2 files changed
+232 -6

No files matched your search

+105
View File
@@ -50,6 +50,111 @@ class NvMapPwScraper():
if not cls._context:
cls._context = await cls._browser.new_context(**cls.default_context_builder())
cls.is_ready = True
GRAPHQL_URL = "https://pcmap-api.place.naver.com/graphql"
_PLACE_TYPES = ("restaurant", "accommodation")
@classmethod
async def fetch_graphql(
cls,
place_id: str,
payloads: list[dict],
place_type: str | None = None,
) -> list[dict | None] | None:
"""실제 브라우저로 네이버 WTM 안티봇 캡차를 통과해 GraphQL 쿼리를 실행한다.
네이버 pcmap GraphQL은 두 헤더를 검사한다:
- x-wtm-graphql : base64({"arg": place_id, "type": ..., "source": "place"})
- x-wtm-ncaptcha-token : 캡차 JS가 생성 (요청마다 발급, 직접 생성 불가)
둘 다 없으면 405(캡차)로 막힌다. 따라서 place 페이지를 실제로 로드해
페이지가 자연 발생시키는 GraphQL 요청에서 두 헤더를 캡처한 뒤,
같은 토큰으로 우리 쿼리들을 in-page fetch로 실행한다.
Args:
place_id: 네이버 place ID
payloads: GraphQL POST 본문 목록
place_type: "restaurant" | "accommodation" (없으면 둘 다 시도)
Returns:
payload별 파싱 JSON 목록(실패 항목은 None). 토큰 캡처 실패 시 None.
"""
if not cls.is_ready:
logger.warning("[NvMapPwScraper] fetch_graphql: scraper가 초기화되지 않았습니다")
return None
page = await cls._context.new_page()
captured: dict = {}
def on_request(req):
if "/graphql" in req.url and req.method == "POST" and "tok" not in captured:
tok = req.headers.get("x-wtm-ncaptcha-token")
if tok:
captured["tok"] = tok
captured["wtm"] = req.headers.get("x-wtm-graphql")
page.on("request", on_request)
try:
types = [place_type] if place_type in cls._PLACE_TYPES else list(cls._PLACE_TYPES)
for t in types:
try:
await page.goto(
f"https://pcmap.place.naver.com/{t}/{place_id}/home",
wait_until="domcontentloaded",
timeout=30000,
)
except Exception as e:
logger.debug(f"[NvMapPwScraper] goto {t} 실패: {e}")
continue
# 페이지가 GraphQL 요청을 보내며 토큰이 헤더에 실릴 때까지 대기 (최대 ~9초)
for _ in range(30):
if captured.get("tok"):
break
await page.wait_for_timeout(300)
if captured.get("tok"):
logger.info(f"[NvMapPwScraper] WTM 토큰 캡처 성공 (type={t})")
break
if not captured.get("tok"):
logger.warning("[NvMapPwScraper] WTM 토큰 캡처 실패")
return None
headers = {
"Content-Type": "application/json",
"x-wtm-graphql": captured["wtm"],
"x-wtm-ncaptcha-token": captured["tok"],
}
results: list[dict | None] = []
for payload in payloads:
r = await page.evaluate(
"""async (a) => {
const [url, body, hdr] = a;
try {
const r = await fetch(url, {
method: 'POST',
headers: hdr,
body: JSON.stringify(body),
credentials: 'include',
});
if (r.status !== 200) return {__err: r.status};
return await r.json();
} catch (e) { return {__err: String(e)}; }
}""",
[cls.GRAPHQL_URL, payload, headers],
)
if isinstance(r, dict) and "__err" in r:
logger.warning(f"[NvMapPwScraper] graphql fetch 실패: {r['__err']}")
results.append(None)
else:
results.append(r)
return results
except Exception as e:
logger.error(f"[NvMapPwScraper] fetch_graphql 오류: {e}")
return None
finally:
await page.close()
def __init__(self):
if not self.is_ready: