import win32gui
import win32process
import psutil
import win32com.client
import pyautogui
import time
import pyperclip
def getChromeWindowInfoDictrionary():
chromeWindowInfoDictionary = []
def enumerateWindowCallback(windowHandle, longParameter):
if win32gui.IsWindowVisible(windowHandle):
_, processID = win32process.GetWindowThreadProcessId(windowHandle)
try:
process = psutil.Process(processID)
if "chrome" in process.name().lower():
windowTitle = win32gui.GetWindowText(windowHandle)
rectangle = win32gui.GetWindowRect(windowHandle)
width = rectangle[2] - rectangle[0]
height = rectangle[3] - rectangle[1]
chromeWindowInfoDictionary.append({"windowHandle" : windowHandle, "title" : windowTitle, "processID" : processID, "width" : width, "height" : height})
except psutil.NoSuchProcess:
pass
win32gui.EnumWindows(enumerateWindowCallback, None)
return chromeWindowInfoDictionary
def getMainChromeWindowInfo(chromeWindowInfoDictionary):
if not chromeWindowInfoDictionary:
return None
mainChromeWindowInfo = max(chromeWindowInfoDictionary, key = lambda w : w["width"] * w["height"])
return mainChromeWindowInfo
def getActiveTabInfo(chromeWindowInfo):
windowHandle = chromeWindowInfo["windowHandle"]
shell = win32com.client.Dispatch("WScript.Shell")
win32gui.SetForegroundWindow(windowHandle)
time.sleep(0.5)
# ALT 키를 누른다.
shell.SendKeys("%")
time.sleep(0.5)
# URL을 복사한다.
# 주소 창을 선택한다.
pyautogui.hotkey("ctrl", "l")
time.sleep(0.1)
# URL을 복사한다.
pyautogui.hotkey("ctrl", "c")
time.sleep(0.1)
# 클립보드에서 복사된 URL을 가져온다.
url = pyperclip.paste()
# HTML을 복사한다.
# 소스 보기 창을 연다.
pyautogui.hotkey("ctrl", "u")
time.sleep(1)
# 전체를 선택한다.
pyautogui.hotkey("ctrl", "a")
time.sleep(0.1)
# HTML을 복사한다.
pyautogui.hotkey("ctrl", "c")
time.sleep(0.1)
# 클립보드에서 복사된 HTML을 가져온다.
html = pyperclip.paste()
# 소스 창을 닫는다.
pyautogui.hotkey("ctrl", "w")
return url, html
chromeWindowDictionary = getChromeWindowInfoDictrionary()
mainChromeWindowInfo = getMainChromeWindowInfo(chromeWindowDictionary)
if mainChromeWindowInfo:
url, html = getActiveTabInfo(mainChromeWindowInfo)
print(f"활성 탭 URL : {url}")
print(f"HTML 코드 : {html[:500]}...") # HTML 코드 일부만 출력한다.
else:
print("실행 중인 크롬 브라우저를 찾을 수 없습니다.")