Resell1/modules/market_actions.py

46 lines
1.8 KiB
Python

import re
import json
import requests
def fetch_sold_products(market_url: str, logger=None) -> dict:
"""
주어진 마켓 URL에서 베스트 상품 페이지(예: https://smartstore.naver.com/modeuda/best?cp=1)에 접속하여
__PRELOADED_STATE__ 항목을 추출하고 JSON 객체로 반환합니다.
Args:
market_url (str): 예를 들어 "https://smartstore.naver.com/modeuda"
logger: 로거 객체가 제공되면 디버그/오류 메시지를 출력합니다.
Returns:
dict: 추출된 __PRELOADED_STATE__ JSON 데이터 (추출 실패 시 빈 dict 반환)
"""
if logger:
logger.debug("Entering fetch_sold_products()")
try:
# 베스트 상품 페이지 URL 생성
best_url = market_url.rstrip('/') + "/best?cp=1"
if logger:
logger.debug(f"Fetching URL: {best_url}")
response = requests.get(best_url)
if response.status_code != 200:
if logger:
logger.error(f"HTTP error {response.status_code} for URL: {best_url}")
return {}
html = response.text
# __PRELOADED_STATE__ 항목을 정규식으로 추출 (비정형 데이터이므로 non-greedy match 사용)
pattern = r'window\.__PRELOADED_STATE__=({.*?});'
match = re.search(pattern, html, re.DOTALL)
if not match:
if logger:
logger.error("Could not find __PRELOADED_STATE__ in the page")
return {}
state_json_str = match.group(1)
state = json.loads(state_json_str)
if logger:
logger.debug("Fetched __PRELOADED_STATE__ successfully")
return state
except Exception as e:
if logger:
logger.error(f"Error in fetch_sold_products: {e}", exc_info=True)
return {}