diff --git a/app/utils/nvMapPwScraper.py b/app/utils/nvMapPwScraper.py index 9dd4a26..e7780e5 100644 --- a/app/utils/nvMapPwScraper.py +++ b/app/utils/nvMapPwScraper.py @@ -1,4 +1,5 @@ import asyncio +import json import random import re from html import unescape @@ -11,6 +12,10 @@ from app.utils.logger import get_logger # 로거 설정 logger = get_logger("pwscraper") +# 주소 동일 위치 판정용 키 패턴: '삼성로85길 26', '대치동 891-46' +_ROAD_KEY = re.compile(r"([가-힣0-9]+(?:대로|로|길))\s*(\d+(?:-\d+)?)") +_JIBUN_KEY = re.compile(r"([가-힣0-9]+(?:동|리|가|읍|면))\s*(\d+(?:-\d+)?)") + class NvMapPwScraper(): # cls vars is_ready = False @@ -22,6 +27,9 @@ class NvMapPwScraper(): _max_retry = 3 _timeout = 30 # place id timeout threshold seconds _retry_delay_ms = 1500 # 검색 실패 후 재시도 전 대기시간 (네이버 요청 밀도 완화) + _MIN_NAME_SCORE = 0.6 # 후보 선정 시 이름 유사도 하한 (미달이면 다른 업체로 간주) + _TIE_MARGIN = 0.02 # 1·2위 후보의 종합 점수 차가 이 값 미만이면 모호하다고 보고 선정하지 않는다 + _last_search_conclusive = False # 마지막 _try_search 가 검색 응답을 받아 판단까지 마쳤는지(재시도 불필요 여부) # UA·뷰포트·sec-ch-ua를 한 세트로 묶은 브라우저 프로필 후보군 (안티봇 핑거프린트 회피용) _UA_PROFILES = [ @@ -325,6 +333,13 @@ if (originalQuery) { logger.debug(f"[DEBUG] pcmap frame content 추출 실패: {e}") return [] + # 1차: iframe HTML에도 list 응답과 같은 __APOLLO_STATE__ 가 들어 있다 (주소 포함, 최대 70개) + apollo_candidates = self._parse_list_candidates(html) + if apollo_candidates: + logger.debug(f"[DEBUG] iframe Apollo state 후보 {len(apollo_candidates)}개 추출") + return apollo_candidates + + # 2차: Apollo state가 없을 때만 정규식으로 id/name 쌍 추출 (주소 없음) # {"id":"11659052","name":"프레지던트 호텔",...} 형태의 JSON 쌍 추출 pair_pattern = re.compile( r'"id"\s*:\s*"(\d{5,})"[^}]{0,200}?"name"\s*:\s*"([^"]{1,60})"' @@ -352,18 +367,36 @@ if (originalQuery) { return candidates @staticmethod - def _parse_allsearch_candidates(body: dict) -> list[dict]: - """allSearch 응답 JSON에서 후보 목록을 추출한다.""" - place_list = (((body.get("result") or {}).get("place") or {}).get("list")) or [] + def _parse_list_candidates(html: str) -> list[dict]: + """검색 결과 list 응답 HTML의 window.__APOLLO_STATE__ 에서 후보 목록을 추출한다. + + roadAddress 에는 시·도가 포함된 fullAddress 를 채운다 (자동완성 항목의 도로명 주소와 + 같은 형식이어야 주소 유사도 비교가 성립한다). + """ + marker = "window.__APOLLO_STATE__ =" + idx = html.find(marker) + if idx < 0: + return [] + brace = html.find("{", idx) + if brace < 0: + return [] + try: + state, _ = json.JSONDecoder().raw_decode(html[brace:]) + except ValueError: + logger.warning("[NvMapPwScraper] __APOLLO_STATE__ JSON 파싱 실패") + return [] + return [ { - "title": p.get("name") or "", - "place_url": f"https://map.naver.com/p/entry/place/{p['id']}", - "roadAddress": p.get("roadAddress") or "", - "address": p.get("address") or "", + "title": item.get("name") or "", + "place_url": f"https://map.naver.com/p/entry/place/{item['id']}", + "roadAddress": item.get("fullAddress") or item.get("roadAddress") or "", + "address": item.get("address") or "", } - for p in place_list - if p.get("id") + for key, item in state.items() + if key.startswith("PlaceListBusinessesItem:") + and isinstance(item, dict) + and item.get("id") ] def _select_best_candidate(self, candidates: list[dict], title: str, address: str) -> dict | None: @@ -384,22 +417,109 @@ if (originalQuery) { return max(candidates, key=lambda c: c["_total_score"]) - async def _capture_allsearch(self, url: str, timeout_s: float = 5.0) -> list[dict]: - """검색 페이지가 자연 발생시키는 allSearch API 응답을 캡처해 후보 목록으로 변환한다. + @staticmethod + def _address_keys(address: str) -> set[str]: + """주소에서 '도로명+번호' / '지번동+번호' 키를 추출한다 (예: '삼성로85길 26', '대치동 891-46'). - pcmap iframe 렌더링을 기다릴 필요가 없어 경쟁 조건이 없고, 업체명 단독 - 검색처럼 iframe 자체가 생성되지 않는 케이스에서도 동작한다. + 문자열 유사도는 같은 도로의 다른 번호(삼성로85길 11 vs 26)도 높게 평가하므로, + 동일 위치 판정은 이 키의 일치 여부로 한다. """ - captured: list[dict] = [] + keys = set() + for pattern in (_ROAD_KEY, _JIBUN_KEY): + for m in pattern.finditer(address or ""): + keys.add(f"{m.group(1)} {m.group(2)}") + return keys + + def _pick_verified_candidate( + self, candidates: list[dict], title: str, address: str, jibun: str = "" + ) -> dict | None: + """후보를 점수화한 뒤 검증을 통과한 후보만 반환한다. 확신할 수 없으면 None (오선정 방지). + + 1. 이름 유사도가 하한(_MIN_NAME_SCORE) 미만이면 제외 + 2. 선택 주소와 후보 주소의 '도로명+번호'/'지번+번호' 키가 하나도 겹치지 않으면 제외 + 3. 남은 후보의 점수 차가 _TIE_MARGIN 미만이면 모호하므로 거부 + 4. 주소로 검증할 수 없는 경우(선택 주소 없음 / 후보에 주소 없음)는 + 이름이 정확히 일치하는 후보가 단 하나일 때만 허용 + """ + if not candidates: + return None + + # 후보별 _name_score/_addr_score/_total_score 를 채운다 (반환값은 사용하지 않음) + self._select_best_candidate(candidates, title, address) + + eligible = [c for c in candidates if c["_name_score"] >= self._MIN_NAME_SCORE] + if not eligible: + logger.warning(f"[AUTO-SELECT] 이름 유사도 하한({self._MIN_NAME_SCORE}) 미달: '{title}'") + return None + + wanted = self._address_keys(address) | self._address_keys(jibun) + with_addr = [ + c for c in eligible + if self._address_keys(c.get("roadAddress", "")) | self._address_keys(c.get("address", "")) + ] + + if wanted and with_addr: + pool = [ + c for c in with_addr + if wanted & (self._address_keys(c.get("roadAddress", "")) | self._address_keys(c.get("address", ""))) + ] + if not pool: + logger.warning(f"[AUTO-SELECT] 주소 불일치로 후보 {len(with_addr)}개 모두 제외: '{title}'") + return None + ranked = sorted(pool, key=lambda c: c["_total_score"], reverse=True) + if len(ranked) > 1 and ranked[0]["_total_score"] - ranked[1]["_total_score"] < self._TIE_MARGIN: + logger.warning(f"[AUTO-SELECT] 동점 후보 {len(ranked)}개로 선정 불가: '{title}'") + return None + return ranked[0] + + exact = [c for c in eligible if c["_name_score"] == 1.0] + if len(exact) == 1: + return exact[0] + logger.warning(f"[AUTO-SELECT] 주소 검증 불가 + 이름 정확 일치 후보 {len(exact)}개로 선정 불가: '{title}'") + return None + + def _select_and_log( + self, candidates: list[dict], title: str, address: str, jibun: str, tag: str = "" + ) -> str | None: + """검증된 후보를 골라 로그를 남기고 place URL을 반환한다. 선정 불가면 None.""" + best = self._pick_verified_candidate(candidates, title, address, jibun) + if not best: + logger.warning(f"[AUTO-SELECT{tag}] 선정 불가 (후보 {len(candidates)}개): '{title}'") + return None + logger.info( + f"[AUTO-SELECT{tag}] '{title}' → '{best['title']}' " + f"(name={best['_name_score']:.2f}, addr={best['_addr_score']:.2f}) {best['place_url']}" + ) + return best["place_url"] + + async def _capture_list_candidates(self, url: str, timeout_s: float = 5.0) -> list[dict] | None: + """검색 페이지가 자연 발생시키는 list(pcmap.place.naver.com/*/list) 응답을 캡처해 후보 목록으로 변환한다. + + 네이버가 allSearch API를 제거하면서 검색 결과는 list 페이지 HTML의 + __APOLLO_STATE__ 로만 내려온다. 주소가 섞인 검색어는 주소 검색으로 처리되어 + 장소 목록이 비므로 업체명만으로 검색해야 한다. + + 반환값: 후보 목록 / 응답은 받았으나 결과 0건이면 [] / list 응답을 받지 못했으면 None + """ + captured: list[list[dict]] = [] def on_response(resp): - # GET 요청의 실제 응답만 캡처 (OPTIONS preflight 등 오탐 방지) - if "allSearch" in resp.url and resp.request.method == "GET": + # GET 200 응답만 캡처 (302 리다이렉트·OPTIONS preflight 오탐 방지) + if ( + "pcmap.place.naver.com" in resp.url + and "/list" in resp.url + and resp.status == 200 + and resp.request.method == "GET" + ): async def _consume(): try: - captured.append(await resp.json()) - except Exception: - pass + html = await resp.text() + except Exception as e: + logger.warning(f"[NvMapPwScraper] list 응답 읽기 실패: {e}") + return + # Apollo state 마커가 없으면 목록 응답이 아니다 (차단 페이지 등) + if "window.__APOLLO_STATE__" in html: + captured.append(self._parse_list_candidates(html)) asyncio.create_task(_consume()) self.page.on("response", on_response) @@ -411,53 +531,58 @@ if (originalQuery) { deadline = time.monotonic() + timeout_s while time.monotonic() < deadline: - if "/place/" in self.page.url or captured: + # 비어 있지 않은 목록이 오거나 /place/ 로 이동하면 종료. 빈 목록만 받았다면 + # 뒤늦게 다른 업종 list 가 오는지 deadline 까지 기다린다. + if "/place/" in self.page.url or any(captured): break await self.page.wait_for_timeout(200) finally: self.page.remove_listener("response", on_response) - if not captured: - return [] - return self._parse_allsearch_candidates(captured[0]) + non_empty = next((c for c in captured if c), None) + if non_empty is not None: + return non_empty + return [] if captured else None - async def _try_search(self, address: str, title: str) -> str | None: - """주어진 주소+업체명으로 검색해서 place URL을 반환한다. 실패 시 None.""" - encoded_query = parse.quote(f"{address} {title}".strip()) + async def _try_search(self, address: str, title: str, jibun: str = "") -> str | None: + """업체명으로 검색해 후보를 받고, 검증을 통과한 후보의 place URL을 반환한다. 실패 시 None. + + 검색어에는 주소를 넣지 않는다 (주소가 섞이면 네이버가 주소 검색으로 처리해 장소 목록이 비어 있음). + address/jibun 은 후보 검증(_pick_verified_candidate)에만 사용한다. + + 검색 응답을 받아 판단까지 마쳤다면(결과 0건 / 검증 실패 포함) _last_search_conclusive 를 True 로 + 남긴다. 재시도해도 결과가 달라지지 않으므로 호출자가 재시도를 생략하는 데 사용한다. + """ + self._last_search_conclusive = False + encoded_query = parse.quote(title) url = f"https://map.naver.com/p/search/{encoded_query}" - # 1순위: allSearch API 응답 캡처 (iframe 렌더링 대기 불필요, 업체명 단독 검색도 지원) - candidates = await self._capture_allsearch(url) + # 1순위: list 응답 캡처 (__APOLLO_STATE__ 파싱) + candidates = await self._capture_list_candidates(url) if "/place/" in self.page.url: return self.page.url - if candidates: - best = self._select_best_candidate(candidates, title, address) - logger.info( - f"[AUTO-SELECT] '{title}' → '{best['title']}' " - f"(name={best['_name_score']:.2f}, addr={best['_addr_score']:.2f}) {best['place_url']}" - ) - return best['place_url'] + if candidates is not None: + self._last_search_conclusive = True + if not candidates: + logger.warning(f"[AUTO-SELECT] 검색 결과 0건: '{title}'") + return None + return self._select_and_log(candidates, title, address, jibun) - # 2순위(안전망): allSearch 캡처 실패 시 기존 iframe HTML 파싱 방식으로 폴백 - # ── 잠시 비활성화 ── - # logger.warning("[FALLBACK] allSearch 캡처 실패 → iframe 파싱 방식 시도") - # iframe_candidates = [] - # for _ in range(3): # 500ms × 3 = 최대 1.5초 - # if "/place/" in self.page.url: - # return self.page.url - # iframe_candidates = await self._extract_candidates_from_list_page() - # if iframe_candidates: - # break - # await self.page.wait_for_timeout(500) - # - # if iframe_candidates: - # best = self._select_best_candidate(iframe_candidates, title, address) - # logger.info( - # f"[AUTO-SELECT-IFRAME] '{title}' → '{best['title']}' " - # f"(name={best['_name_score']:.2f}, addr={best['_addr_score']:.2f}) {best['place_url']}" - # ) - # return best['place_url'] + # 2순위(안전망): list 응답을 받지 못했을 때 렌더된 iframe HTML 에서 후보 추출 + logger.warning("[FALLBACK] list 응답 캡처 실패 → iframe 파싱 방식 시도") + iframe_candidates = [] + for _ in range(10): # 500ms × 10 = 최대 5초 (iframe 렌더링은 4~7초까지 걸릴 수 있음) + if "/place/" in self.page.url: + return self.page.url + iframe_candidates = await self._extract_candidates_from_list_page() + if iframe_candidates: + break + await self.page.wait_for_timeout(500) + + if iframe_candidates: + self._last_search_conclusive = True + return self._select_and_log(iframe_candidates, title, address, jibun, "-IFRAME") # isCorrectAnswer=true 로 강제 단일결과 재시도 (원본 로직 유지) correct_url = self.page.url.replace("?", "?isCorrectAnswer=true&") @@ -475,36 +600,35 @@ if (originalQuery) { async def get_place_id_url(self, selected): title = self._clean_title(selected['title']) - address = self._clean_title(selected.get('roadAddress', selected['address'])) + # roadAddress 가 빈 문자열/None 이면 지번 주소로 대체 (dict.get 기본값은 키가 있으면 적용되지 않음) + jibun = self._clean_title(selected.get('address') or '') + address = self._clean_title(selected.get('roadAddress') or selected.get('address') or '') - # 1차 시도: 원본 주소 + 업체명 - logger.debug(f"[DEBUG] 1차 시도 - address: {address}") - result = await self._try_search(address, title) + # 1차 시도: 업체명 검색 + 주소 검증으로 후보 선정 + logger.debug(f"[DEBUG] 1차 시도 - title: {title}, address: {address}") + result = await self._try_search(address, title, jibun) if result: return result + if self._last_search_conclusive: + logger.warning(f"[NOT-FOUND] 검색 응답은 받았으나 일치하는 업체 없음 → 재시도 생략: '{title}'") + return None - # 2차 시도: 정제 주소 + 업체명 - refined = self._refine_address(address) - if refined != address: - await self.page.wait_for_timeout(self._retry_delay_ms) - logger.info(f"[REFINE] 주소 정제: '{address}' → '{refined}'") - result = await self._try_search(refined, title) - if result: - return result - - # 3차 시도: 업체명만으로 검색 + # 2차 시도: 일시적 실패 대비 재시도 await self.page.wait_for_timeout(self._retry_delay_ms) - logger.info(f"[RETRY] 업체명만으로 재시도: '{title}'") - result = await self._try_search("", title) + logger.info(f"[RETRY] 재시도: '{title}'") + result = await self._try_search(address, title, jibun) if result: return result + if self._last_search_conclusive: + logger.warning(f"[NOT-FOUND] 검색 응답은 받았으나 일치하는 업체 없음 → 재시도 생략: '{title}'") + return None - # 1~3차 모두 실패 → 네이버 안티봇 차단 의심, 컨텍스트 재생성 후 원본 조건으로 1회 재시도 - logger.warning(f"[BLOCK-SUSPECTED] 3회 시도 모두 실패 → 컨텍스트 재생성 후 재시도: '{title}'") + # 1~2차 모두 실패 → 네이버 안티봇 차단 의심, 컨텍스트 재생성 후 1회 재시도 + logger.warning(f"[BLOCK-SUSPECTED] 2회 시도 모두 실패 → 컨텍스트 재생성 후 재시도: '{title}'") await self.page.close() await self._recreate_context() await self.create_page() - result = await self._try_search(address, title) + result = await self._try_search(address, title, jibun) if result: return result