114 lines
4.7 KiB
Python
114 lines
4.7 KiB
Python
from pywinauto import Application, findwindows, timings
|
|
from pywinauto.timings import wait_until
|
|
|
|
import time, pyperclip, os
|
|
import logging, json
|
|
from lens_parser import ShoppingLensScraper # ShoppingLensScraper를 import
|
|
|
|
# 로깅 설정
|
|
logging.basicConfig(level=logging.DEBUG, format="%(asctime)s [%(levelname)s] %(message)s")
|
|
logger = logging.getLogger(__name__)
|
|
|
|
# 쇼핑 렌즈 스크래퍼 초기화
|
|
lens_parser = ShoppingLensScraper(None, logger)
|
|
|
|
url = 'https://file.percenty.co.kr/public/652bed8e865b1f32ea62bf1f/products/6734dc6f9acd55067354225d/0c0fbc92-e52a-4e8e-982e-036b224eb71a.jpg'
|
|
|
|
whale_exe_path = os.path.join(os.getcwd(), "browsers", "whale", "whale.exe")
|
|
user_data_dir = os.path.join(os.getcwd(), "browsers", "whale", "user_data")
|
|
cache_dir = os.path.join(os.getcwd(), "browsers", "whale", "cache")
|
|
|
|
# 웨일 실행
|
|
whale_app = Application(backend="uia").start(
|
|
f'"{whale_exe_path}" --user-data-dir="{user_data_dir}" --disk-cache-dir="{cache_dir}"'
|
|
)
|
|
|
|
timings.wait_until(10, 0.5, lambda: any(window.name == '새 탭 - Whale' for window in findwindows.find_elements()))
|
|
|
|
# '새 탭 - Whale' 창의 PID 검색
|
|
whale_pid = None
|
|
windows = findwindows.find_elements()
|
|
|
|
for window in windows:
|
|
if window.name == '새 탭 - Whale':
|
|
whale_pid = window.process_id
|
|
logger.info(f"'새 탭 - Whale' 창을 찾았습니다. PID: {whale_pid}")
|
|
break
|
|
|
|
# PID를 통해 웨일 창 제어
|
|
if whale_pid:
|
|
try:
|
|
whale_app = Application(backend="uia").connect(process=whale_pid)
|
|
whale_window = whale_app.top_window()
|
|
|
|
# 창 포커스 설정
|
|
whale_window.set_focus()
|
|
logger.info("=== 초기 상태 ===")
|
|
|
|
# URL 이동
|
|
address_bar = whale_window.child_window(title="주소창 및 검색창", control_type="Edit")
|
|
address_bar.click_input()
|
|
|
|
# URL 문자열을 직접 입력
|
|
for chunk in [url[i:i+10] for i in range(0, len(url), 10)]:
|
|
address_bar.type_keys(chunk, with_spaces=True)
|
|
address_bar.type_keys("{ENTER}") # 엔터 입력
|
|
logger.info(f"{url}로 이동 중...")
|
|
|
|
# 이미지 우클릭 및 쇼핑 렌즈 활성화
|
|
print(f"이미지 우클릭")
|
|
try:
|
|
image = whale_window.child_window(title="누락된 이미지 설명을 확인하려면 컨텍스트 메뉴를 여세요.", control_type="Image")
|
|
|
|
if image.exists():
|
|
image.right_click_input()
|
|
logger.info("이미지 요소에서 우클릭을 수행했습니다.")
|
|
|
|
shoppingLens_menu_item = whale_window.child_window(title="쇼핑렌즈로 검색하기", control_type="MenuItem")
|
|
shoppingLens_menu_item.click_input()
|
|
logger.info("쇼핑 렌즈 검색 명령이 실행되었습니다.")
|
|
|
|
# ListBox 요소가 나타날 때까지 대기
|
|
wait_until(
|
|
timeout=10,
|
|
retry_interval=0.5,
|
|
# func=lambda: whale_window.child_window(control_type="Hyperlink").exists()
|
|
func=lambda: whale_window.child_window(title="본문 바로가기", control_type="Hyperlink").exists()
|
|
|
|
)
|
|
logger.info("쇼핑 렌즈 검색 결과가 나타났습니다.")
|
|
time.sleep(4)
|
|
|
|
# 모든 Hyperlink 요소의 title 값을 가져오기
|
|
hyperlinks = whale_window.descendants(control_type="Hyperlink")
|
|
titles = [hyperlink.window_text() for hyperlink in hyperlinks]
|
|
|
|
filter_titles = lens_parser.filter_titles(titles)
|
|
# 결과 출력
|
|
logger.info(f"수집한 Hyperlink Titles: {len(filter_titles)} 개")
|
|
# logger.info(f"{filter_titles}")
|
|
|
|
# 쇼핑 렌즈 데이터 스크래핑
|
|
products = {}
|
|
products = lens_parser.parse_product_info(titles=filter_titles)
|
|
|
|
logger.info(f"스크래핑 완료. 추출된 데이터: {len(products)}")
|
|
for product in products:
|
|
print(product)
|
|
print(f"\n")
|
|
|
|
|
|
# 데이터를 JSON 파일로 저장 (필요 시)
|
|
with open("shopping_results1.json", "w", encoding="utf-8") as file:
|
|
json.dump(products, file, ensure_ascii=False, indent=4)
|
|
|
|
else:
|
|
logger.warning("이미지 요소를 찾을 수 없습니다.")
|
|
except Exception as e:
|
|
logger.error(f"이미지 요소에서 우클릭 중 오류 발생: {e}", exc_info=True)
|
|
|
|
except Exception as e:
|
|
logger.error(f"창을 제어할 수 없습니다: {e}", exc_info=True)
|
|
else:
|
|
logger.error("'새 탭 - Whale' 창을 찾을 수 없습니다.")
|