테스트 성공코드 main2.py
This commit is contained in:
parent
24c9b97eae
commit
e3d70846cf
|
|
@ -0,0 +1,133 @@
|
|||
import time
|
||||
from pywinauto import Application, findwindows, keyboard
|
||||
import os
|
||||
|
||||
def start_whale_in_secret_mode():
|
||||
# 실행 경로 설정
|
||||
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")
|
||||
|
||||
# # 유저 데이터 및 캐시 폴더 비우기
|
||||
# clear_directory(user_data_dir)
|
||||
# clear_directory(cache_dir)
|
||||
|
||||
# 웨일을 시크릿 모드로 시작
|
||||
app = Application(backend="uia").start(
|
||||
f'"{whale_exe_path}" --incognito --auto-open-devtools-for-tabs --user-data-dir="{user_data_dir}" --disk-cache-dir="{cache_dir}"'
|
||||
)
|
||||
time.sleep(1) # 웨일이 완전히 로드될 때까지 대기
|
||||
return app
|
||||
|
||||
def find_whale_window(app):
|
||||
# '새 시크릿 탭 - Whale' 창을 찾기 위해 PID 검색
|
||||
whale_pid = None
|
||||
windows = findwindows.find_elements()
|
||||
for window in windows:
|
||||
if window.name == '새 시크릿 탭 - Whale':
|
||||
whale_pid = window.process_id
|
||||
break
|
||||
|
||||
# PID가 있으면 해당 창을 연결
|
||||
if whale_pid:
|
||||
app = Application(backend="uia").connect(process=whale_pid)
|
||||
whale_window = app.top_window()
|
||||
whale_window.set_focus()
|
||||
return whale_window
|
||||
else:
|
||||
print("'새 시크릿 탭 - Whale' 창을 찾을 수 없습니다.")
|
||||
return None
|
||||
|
||||
def navigate_to_url(whale_window, url):
|
||||
# 주소창을 찾고 URL을 입력 후 이동
|
||||
try:
|
||||
address_bar = whale_window.child_window(title="주소창 및 검색창", control_type="Edit")
|
||||
address_bar.click_input()
|
||||
address_bar.type_keys(f"{url}{{ENTER}}", with_spaces=True)
|
||||
time.sleep(1) # 페이지 로딩 대기
|
||||
except Exception as e:
|
||||
print(f"주소창에 접근할 수 없습니다: {e}")
|
||||
|
||||
def right_click_on_image_and_inspect(whale_window):
|
||||
try:
|
||||
# 이미지 요소를 찾아서 우클릭
|
||||
image = whale_window.child_window(title="누락된 이미지 설명을 확인하려면 컨텍스트 메뉴를 여세요.", control_type="Image")
|
||||
|
||||
if image.exists():
|
||||
image.right_click_input()
|
||||
print("이미지 요소에서 우클릭을 수행했습니다.")
|
||||
else:
|
||||
print("이미지 요소를 찾을 수 없습니다.")
|
||||
return
|
||||
|
||||
# “이미지 번역” 메뉴 항목 클릭
|
||||
translate_menu_item = whale_window.child_window(title="이미지 번역 (R)", control_type="MenuItem")
|
||||
translate_menu_item.click_input()
|
||||
print("이미지 번역 명령이 실행되었습니다.")
|
||||
|
||||
# 번역이 실행된 후 대기
|
||||
time.sleep(2)
|
||||
|
||||
# auto_id="elements-content" 요소 클릭
|
||||
elements_content = whale_window.child_window(auto_id="elements-content", control_type="Group")
|
||||
if elements_content.exists():
|
||||
elements_content.click_input()
|
||||
print("elements-content 요소를 클릭했습니다.")
|
||||
|
||||
# Ctrl+F로 검색 창 활성화
|
||||
keyboard.send_keys("^f")
|
||||
time.sleep(1) # 검색 창이 열릴 시간을 대기
|
||||
|
||||
# search-input-field에 'data:image' 입력
|
||||
search_input = whale_window.child_window(auto_id="search-input-field", control_type="Edit")
|
||||
if search_input.exists():
|
||||
search_input.click_input()
|
||||
search_input.type_keys("data:image", with_spaces=True)
|
||||
print("search-input-field 요소에 'data:image'를 입력했습니다.")
|
||||
time.sleep(1) # 검색 결과가 로드될 시간을 대기
|
||||
# whale_window.print_control_identifiers()
|
||||
# time.sleep(1) # 검색 결과가 로드될 시?간을 대기
|
||||
|
||||
# data:image로 시작하는 Hyperlink 요소 검색 및 출력
|
||||
try:
|
||||
# 지정한 기준으로 모든 매칭 요소 가져오기
|
||||
image_elements = whale_window.children(control_type="TreeItem")
|
||||
|
||||
# title이 '^<img'로 시작하는 모든 TreeItem 요소 중에서 두 번째 요소 선택
|
||||
matching_elements = [elem for elem in image_elements if elem.window_text().startswith("<img")]
|
||||
|
||||
if len(matching_elements) >= 2:
|
||||
# 두 번째 요소 선택
|
||||
second_image_element = matching_elements[1]
|
||||
|
||||
# 두 번째 요소에서 우클릭 수행
|
||||
second_image_element.right_click_input()
|
||||
print("두 번째 이미지 요소에서 우클릭을 수행했습니다.")
|
||||
|
||||
# 두 번째 요소의 상세 정보 출력
|
||||
print("\n=== 두 번째 이미지 요소의 상세 정보 ===")
|
||||
second_image_element.print_control_identifiers()
|
||||
|
||||
else:
|
||||
print("해당 조건에 맞는 두 번째 요소를 찾을 수 없습니다.")
|
||||
|
||||
except Exception as e:
|
||||
print(f"이미지 요소에서 우클릭 또는 요소 찾기 중 오류 발생: {e}")
|
||||
|
||||
else:
|
||||
print("search-input-field 요소를 찾을 수 없습니다.")
|
||||
|
||||
else:
|
||||
print("elements-content 요소를 찾을 수 없습니다.")
|
||||
|
||||
except Exception as e:
|
||||
print(f"이미지 요소에서 우클릭 또는 요소 찾기 중 오류 발생: {e}")
|
||||
|
||||
# 실행 순서
|
||||
if __name__ == "__main__":
|
||||
app = start_whale_in_secret_mode()
|
||||
whale_window = find_whale_window(app)
|
||||
|
||||
if whale_window:
|
||||
navigate_to_url(whale_window, "https://file.percenty.co.kr/public/652bed8e865b1f32ea62bf1f/products/672868c99acd550673510816/0da24e66-a33b-483d-b8a2-bd5b909d8aff.jpg")
|
||||
right_click_on_image_and_inspect(whale_window)
|
||||
|
|
@ -0,0 +1,148 @@
|
|||
import time
|
||||
from pywinauto import Application, findwindows, clipboard
|
||||
import os
|
||||
import logging
|
||||
|
||||
# 로깅 설정
|
||||
logging.basicConfig(level=logging.DEBUG, format="%(asctime)s [%(levelname)s] %(message)s")
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
def start_whale_in_secret_mode():
|
||||
# 실행 경로 설정
|
||||
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")
|
||||
|
||||
# 웨일을 시크릿 모드로 시작
|
||||
app = Application(backend="uia").start(
|
||||
f'"{whale_exe_path}" --incognito --user-data-dir="{user_data_dir}" --disk-cache-dir="{cache_dir}"'
|
||||
)
|
||||
time.sleep(1) # 웨일이 완전히 로드될 때까지 대기
|
||||
return app
|
||||
|
||||
def find_whale_window(app):
|
||||
# '새 시크릿 탭 - Whale' 창을 찾기 위해 PID 검색
|
||||
whale_pid = None
|
||||
windows = findwindows.find_elements()
|
||||
for window in windows:
|
||||
if window.name == '새 시크릿 탭 - Whale':
|
||||
whale_pid = window.process_id
|
||||
break
|
||||
|
||||
# PID가 있으면 해당 창을 연결
|
||||
if whale_pid:
|
||||
app = Application(backend="uia").connect(process=whale_pid)
|
||||
whale_window = app.top_window()
|
||||
whale_window.set_focus()
|
||||
return whale_window
|
||||
else:
|
||||
logger.debug("'새 시크릿 탭 - Whale' 창을 찾을 수 없습니다.")
|
||||
return None
|
||||
|
||||
def navigate_to_url(whale_window, url):
|
||||
# 주소창을 찾고 URL을 입력 후 이동
|
||||
try:
|
||||
address_bar = whale_window.child_window(title="주소창 및 검색창", control_type="Edit")
|
||||
address_bar.click_input()
|
||||
address_bar.type_keys(f"{url}{{ENTER}}", with_spaces=True)
|
||||
time.sleep(3) # 페이지 로딩 대기
|
||||
except Exception as e:
|
||||
logger.debug(f"주소창에 접근할 수 없습니다: {e}", exc_info=True)
|
||||
|
||||
def check_translation_status(whale_window, max_wait_time=10, check_interval=1):
|
||||
start_time = time.time()
|
||||
|
||||
while time.time() - start_time < max_wait_time:
|
||||
try:
|
||||
# 번역 실패 검사
|
||||
fail_indicator = whale_window.child_window(title="번역할 영역을 선택하세요.", control_type="Text")
|
||||
if fail_indicator.exists():
|
||||
logger.debug("번역 실패: '번역할 영역을 선택하세요.' 문구가 나타났습니다.")
|
||||
return "fail"
|
||||
|
||||
# 번역 성공 확인을 위한 우클릭 및 이미지 복사
|
||||
image_element = whale_window.child_window(title="누락된 이미지 설명을 확인하려면 컨텍스트 메뉴를 여세요.", control_type="Image")
|
||||
if image_element.exists():
|
||||
image_element.right_click_input()
|
||||
success_indicator = whale_window.child_window(title="이미지 복사(C)", control_type="MenuItem")
|
||||
|
||||
if success_indicator.wait('visible', timeout=5):
|
||||
success_indicator.click_input()
|
||||
time.sleep(0.5) # 클립보드에 이미지가 복사될 시간을 대기
|
||||
|
||||
# 클립보드에서 이미지 데이터 검사
|
||||
try:
|
||||
formats = clipboard.GetClipboardFormats()
|
||||
logger.debug(f"클립보드에 있는 형식 목록: {formats}")
|
||||
|
||||
for format_id in formats:
|
||||
format_name = clipboard.GetFormatName(format_id)
|
||||
logger.debug(f"형식 ID {format_id}: {format_name}")
|
||||
|
||||
if format_name in ("CF_BITMAP", "CF_DIB"):
|
||||
image_data = clipboard.GetData(format_id=format_id)
|
||||
if isinstance(image_data, bytes):
|
||||
logger.info("번역 성공: 클립보드에 이미지 데이터가 있습니다.")
|
||||
return "success"
|
||||
logger.info("번역이 아직 완료되지 않았습니다. 다시 시도 중...")
|
||||
|
||||
except Exception as e:
|
||||
logger.error("클립보드 접근 중 오류 발생", exc_info=True)
|
||||
|
||||
# 체크 주기 대기
|
||||
time.sleep(check_interval)
|
||||
|
||||
except Exception as e:
|
||||
logger.error("번역 상태 확인 중 오류 발생", exc_info=True)
|
||||
return "error"
|
||||
|
||||
logger.debug("번역 확인 시간 초과.")
|
||||
return "timeout"
|
||||
|
||||
def right_click_on_image_and_inspect(whale_window):
|
||||
# 창의 중앙 좌표 계산 및 이미지를 우클릭하여 번역 메뉴 열기
|
||||
try:
|
||||
image = whale_window.child_window(title="누락된 이미지 설명을 확인하려면 컨텍스트 메뉴를 여세요.", control_type="Image")
|
||||
|
||||
if image.exists():
|
||||
image.right_click_input()
|
||||
logger.debug("이미지 요소에서 우클릭을 수행했습니다.")
|
||||
else:
|
||||
logger.debug("이미지 요소를 찾을 수 없습니다.")
|
||||
return
|
||||
|
||||
# “이미지 번역” 클릭
|
||||
translate_menu_item = whale_window.child_window(title="이미지 번역 (R)", control_type="MenuItem")
|
||||
translate_menu_item.click_input()
|
||||
logger.debug("이미지 번역 명령이 실행되었습니다.")
|
||||
|
||||
# 번역이 실행된 후 대기
|
||||
time.sleep(0.5)
|
||||
|
||||
# 번역된 이미지를 확인하기 위해 whale-ocr 요소의 "Expand" 버튼 클릭
|
||||
try:
|
||||
|
||||
status = check_translation_status(whale_window)
|
||||
|
||||
if status == "success":
|
||||
logger.debug("번역이 성공적으로 완료되었습니다.")
|
||||
elif status == "fail":
|
||||
logger.debug("번역에 실패했습니다.")
|
||||
else:
|
||||
logger.debug("번역 상태를 확인할 수 없습니다.")
|
||||
|
||||
except Exception as e:
|
||||
logger.debug(f"번역 실패요소 찾는 중 오류 발생: {e}", exc_info=True)
|
||||
|
||||
except Exception as e:
|
||||
logger.debug(f"이미지 요소에서 우클릭 중 오류 발생: {e}", exc_info=True)
|
||||
|
||||
# 실행 순서
|
||||
if __name__ == "__main__":
|
||||
app = start_whale_in_secret_mode()
|
||||
whale_window = find_whale_window(app)
|
||||
|
||||
if whale_window:
|
||||
navigate_to_url(whale_window, "https://file.percenty.co.kr/public/652bed8e865b1f32ea62bf1f/products/672868829acd5506735107f8/180ba4a3-c38a-418c-98fd-e0aca1b1d221.jpg")
|
||||
# navigate_to_url(whale_window, "https://img.alicdn.com/imgextra/i3/2206707238989/O1CN01q5dVHX2GH1EgiFpIR_!!2206707238989.jpg_Q75.jpg")
|
||||
right_click_on_image_and_inspect(whale_window)
|
||||
|
|
@ -0,0 +1,154 @@
|
|||
import time
|
||||
import os
|
||||
import logging
|
||||
from pywinauto import Application, findwindows, clipboard
|
||||
|
||||
# 로깅 설정
|
||||
logging.basicConfig(level=logging.DEBUG, format="%(asctime)s [%(levelname)s] %(message)s")
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class WhaleTranslator:
|
||||
def __init__(self):
|
||||
self.app = None
|
||||
self.whale_window = None
|
||||
|
||||
def start_whale_in_secret_mode(self):
|
||||
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")
|
||||
|
||||
self.app = Application(backend="uia").start(
|
||||
f'"{whale_exe_path}" --incognito --user-data-dir="{user_data_dir}" --disk-cache-dir="{cache_dir}"'
|
||||
)
|
||||
time.sleep(1)
|
||||
logger.debug("웨일 시크릿 모드로 시작 완료.")
|
||||
|
||||
def find_whale_window(self):
|
||||
windows = findwindows.find_elements()
|
||||
for window in windows:
|
||||
if window.name == '새 시크릿 탭 - Whale':
|
||||
whale_pid = window.process_id
|
||||
self.app = Application(backend="uia").connect(process=whale_pid)
|
||||
self.whale_window = self.app.top_window()
|
||||
self.whale_window.set_focus()
|
||||
logger.debug("웨일 창을 성공적으로 찾았습니다.")
|
||||
return
|
||||
logger.debug("'새 시크릿 탭 - Whale' 창을 찾을 수 없습니다.")
|
||||
|
||||
def navigate_to_url(self, url):
|
||||
"""주소창에 URL을 입력하고 페이지 로딩을 대기"""
|
||||
try:
|
||||
address_bar = self.whale_window.child_window(title="주소창 및 검색창", control_type="Edit")
|
||||
address_bar.click_input()
|
||||
address_bar.type_keys(f"{url}{{ENTER}}", with_spaces=True)
|
||||
logger.debug(f"{url}로 이동 중...")
|
||||
|
||||
# 5초 동안 0.1초 간격으로 이미지 요소가 나타나는지 검사
|
||||
start_time = time.time()
|
||||
while time.time() - start_time < 5:
|
||||
try:
|
||||
# 특정 이미지 요소를 찾으면 즉시 반환
|
||||
image_element = self.whale_window.child_window(title="누락된 이미지 설명을 확인하려면 컨텍스트 메뉴를 여세요.", control_type="Image")
|
||||
if image_element.exists(timeout=0.5):
|
||||
logger.debug("페이지 로딩 완료: 이미지 요소가 나타났습니다.")
|
||||
return
|
||||
except Exception:
|
||||
pass # 요소가 아직 나타나지 않은 경우 대기
|
||||
|
||||
logger.debug("지정된 시간 내에 이미지 요소를 찾지 못했습니다.")
|
||||
except Exception as e:
|
||||
logger.error(f"주소창에 접근할 수 없습니다: {e}", exc_info=True)
|
||||
|
||||
def check_translation_status(self, max_wait_time=10, check_interval=1):
|
||||
start_time = time.time()
|
||||
|
||||
while time.time() - start_time < max_wait_time:
|
||||
try:
|
||||
fail_indicator = self.whale_window.child_window(title="번역할 영역을 선택하세요.", control_type="Text")
|
||||
if fail_indicator.exists():
|
||||
logger.debug("번역 실패: '번역할 영역을 선택하세요.' 문구가 나타났습니다.")
|
||||
return "fail"
|
||||
|
||||
image_element = self.whale_window.child_window(title="누락된 이미지 설명을 확인하려면 컨텍스트 메뉴를 여세요.", control_type="Image")
|
||||
if image_element.exists():
|
||||
image_element.right_click_input()
|
||||
success_indicator = self.whale_window.child_window(title="이미지 복사(C)", control_type="MenuItem")
|
||||
|
||||
if success_indicator.wait('visible', timeout=5):
|
||||
success_indicator.click_input()
|
||||
time.sleep(0.5)
|
||||
|
||||
formats = clipboard.GetClipboardFormats()
|
||||
# logger.debug(f"클립보드에 있는 형식 목록: {formats}")
|
||||
|
||||
for format_id in formats:
|
||||
format_name = clipboard.GetFormatName(format_id)
|
||||
# logger.debug(f"형식 ID {format_id}: {format_name}")
|
||||
|
||||
if format_name in ("CF_BITMAP", "CF_DIB"):
|
||||
image_data = clipboard.GetData(format_id=format_id)
|
||||
if isinstance(image_data, bytes):
|
||||
logger.info("번역 성공: 클립보드에 이미지 데이터가 있습니다.")
|
||||
return "success"
|
||||
logger.info("번역이 아직 완료되지 않았습니다. 다시 시도 중...")
|
||||
|
||||
except Exception as e:
|
||||
logger.error("클립보드 접근 중 오류 발생", exc_info=True)
|
||||
return "error"
|
||||
|
||||
time.sleep(check_interval)
|
||||
|
||||
logger.debug("번역 확인 시간 초과.")
|
||||
return "timeout"
|
||||
|
||||
def right_click_on_image_and_inspect(self):
|
||||
try:
|
||||
image = self.whale_window.child_window(title="누락된 이미지 설명을 확인하려면 컨텍스트 메뉴를 여세요.", control_type="Image")
|
||||
|
||||
if image.exists():
|
||||
image.right_click_input()
|
||||
logger.debug("이미지 요소에서 우클릭을 수행했습니다.")
|
||||
else:
|
||||
logger.debug("이미지 요소를 찾을 수 없습니다.")
|
||||
return
|
||||
|
||||
translate_menu_item = self.whale_window.child_window(title="이미지 번역 (R)", control_type="MenuItem")
|
||||
translate_menu_item.click_input()
|
||||
logger.debug("이미지 번역 명령이 실행되었습니다.")
|
||||
time.sleep(0.5)
|
||||
|
||||
status = self.check_translation_status()
|
||||
if status == "success":
|
||||
logger.debug("번역이 성공적으로 완료되었습니다.")
|
||||
elif status == "fail":
|
||||
logger.debug("번역에 실패했습니다.")
|
||||
else:
|
||||
logger.debug("번역 상태를 확인할 수 없습니다.")
|
||||
|
||||
except Exception as e:
|
||||
logger.debug(f"이미지 요소에서 우클릭 중 오류 발생: {e}", exc_info=True)
|
||||
|
||||
def close_whale_window(self):
|
||||
"""웨일 창을 종료하는 메서드."""
|
||||
try:
|
||||
if self.app:
|
||||
self.app.kill()
|
||||
logger.debug("웨일 창을 성공적으로 종료했습니다.")
|
||||
else:
|
||||
logger.debug("웨일 애플리케이션이 시작되지 않았습니다.")
|
||||
except Exception as e:
|
||||
logger.error("웨일 창을 종료하는 중 오류 발생", exc_info=True)
|
||||
|
||||
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
translator = WhaleTranslator()
|
||||
translator.start_whale_in_secret_mode()
|
||||
translator.find_whale_window()
|
||||
|
||||
if translator.whale_window:
|
||||
translator.navigate_to_url("https://file.percenty.co.kr/public/652bed8e865b1f32ea62bf1f/products/6728687c9acd5506735107f6/1a76bdfe-57f9-4ff5-9280-588b8eb38826.jpg")
|
||||
translator.right_click_on_image_and_inspect()
|
||||
|
||||
translator.close_whale_window()
|
||||
|
|
@ -0,0 +1,116 @@
|
|||
import time
|
||||
import os
|
||||
from pywinauto import Application, clipboard, findwindows
|
||||
|
||||
def start_whale_with_devtools():
|
||||
# 실행 경로 설정
|
||||
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")
|
||||
|
||||
# # 유저 데이터 및 캐시 폴더 비우기
|
||||
# clear_directory(user_data_dir)
|
||||
# clear_directory(cache_dir)
|
||||
|
||||
# 웨일을 시크릿 모드로 시작
|
||||
app = Application(backend="uia").start(
|
||||
f'"{whale_exe_path}" --incognito --auto-open-devtools-for-tabs --user-data-dir="{user_data_dir}" --disk-cache-dir="{cache_dir}"'
|
||||
)
|
||||
time.sleep(1) # 웨일이 완전히 로드될 때까지 대기
|
||||
return app
|
||||
|
||||
def find_whale_window(app):
|
||||
# '새 시크릿 탭 - Whale' 창을 찾기 위해 PID 검색
|
||||
whale_pid = None
|
||||
windows = findwindows.find_elements()
|
||||
for window in windows:
|
||||
if window.name == '새 시크릿 탭 - Whale':
|
||||
whale_pid = window.process_id
|
||||
break
|
||||
|
||||
# PID가 있으면 해당 창을 연결
|
||||
if whale_pid:
|
||||
app = Application(backend="uia").connect(process=whale_pid)
|
||||
whale_window = app.top_window()
|
||||
whale_window.set_focus()
|
||||
return whale_window
|
||||
else:
|
||||
print("'새 시크릿 탭 - Whale' 창을 찾을 수 없습니다.")
|
||||
return None
|
||||
|
||||
|
||||
def navigate_to_url(whale_window, url):
|
||||
# 주소창에 URL 입력 후 이동
|
||||
try:
|
||||
address_bar = whale_window.child_window(title="주소창 및 검색창", control_type="Edit")
|
||||
address_bar.click_input()
|
||||
address_bar.type_keys(f"{url}{{ENTER}}", with_spaces=True)
|
||||
time.sleep(3) # 페이지 로딩 대기
|
||||
except Exception as e:
|
||||
print(f"URL로 이동 중 오류 발생: {e}")
|
||||
|
||||
def right_click_translate_image(whale_window):
|
||||
# 창의 중앙에서 우클릭하여 “이미지 번역” 옵션 클릭
|
||||
try:
|
||||
rect = whale_window.rectangle()
|
||||
center_x = (rect.left + rect.right) // 2
|
||||
center_y = (rect.top + rect.bottom) // 2
|
||||
|
||||
# 중앙에서 우클릭
|
||||
whale_window.right_click_input(coords=(center_x, center_y))
|
||||
time.sleep(1)
|
||||
|
||||
# “이미지 번역” 클릭
|
||||
translate_menu_item = whale_window.child_window(title="이미지 번역 (R)", control_type="MenuItem")
|
||||
translate_menu_item.click_input()
|
||||
print("이미지 번역 명령이 실행되었습니다.")
|
||||
time.sleep(2) # 번역 프로세스 대기
|
||||
except Exception as e:
|
||||
print(f"이미지 번역 실행 중 오류 발생: {e}")
|
||||
|
||||
def execute_js_via_clipboard(whale_window, js_code):
|
||||
# 자바스크립트 코드를 클립보드에 복사하고 주소창에 붙여넣어 실행
|
||||
try:
|
||||
address_bar = whale_window.child_window(title="주소창 및 검색창", control_type="Edit")
|
||||
address_bar.click_input()
|
||||
|
||||
# 자바스크립트 코드를 클립보드에 복사
|
||||
clipboard.EmptyClipboard()
|
||||
clipboard.SetData(f"javascript:{js_code}")
|
||||
|
||||
# 주소창에 붙여넣기 (Ctrl+V)
|
||||
address_bar.type_keys("^v")
|
||||
address_bar.type_keys("{ENTER}")
|
||||
time.sleep(2) # 코드 실행 대기
|
||||
except Exception as e:
|
||||
print(f"자바스크립트 실행 오류: {e}")
|
||||
|
||||
def main():
|
||||
app = start_whale_with_devtools()
|
||||
whale_window = find_whale_window(app)
|
||||
|
||||
if whale_window:
|
||||
url = "https://file.percenty.co.kr/public/652bed8e865b1f32ea62bf1f/products/672868c99acd550673510816/0da24e66-a33b-483d-b8a2-bd5b909d8aff.jpg"
|
||||
navigate_to_url(whale_window, url)
|
||||
right_click_translate_image(whale_window)
|
||||
|
||||
# 번역 상태 추적을 위한 JavaScript 코드
|
||||
js_code = """
|
||||
(function() {
|
||||
const checkStatus = setInterval(() => {
|
||||
const imgElement = document.querySelector("img[src*='base64']");
|
||||
if (imgElement) {
|
||||
console.log("번역 성공 - 이미지 src:", imgElement.src);
|
||||
clearInterval(checkStatus);
|
||||
} else if (document.querySelector(".error:not([hidden])")) {
|
||||
console.log("번역 실패 메시지 감지됨");
|
||||
clearInterval(checkStatus);
|
||||
}
|
||||
}, 500);
|
||||
})();
|
||||
"""
|
||||
|
||||
execute_js_via_clipboard(whale_window, js_code)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Loading…
Reference in New Issue