■ 실행중인 크롬 브라우저의 활성탭에서 URL과 HTML을 구하는 방법을 보여준다.
▶ main.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
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("실행 중인 크롬 브라우저를 찾을 수 없습니다.") |
▶ requirements.txt
1 2 3 4 5 6 7 8 9 10 11 12 |
MouseInfo==0.1.3 psutil==6.0.0 PyAutoGUI==0.9.54 PyGetWindow==0.0.9 PyMsgBox==1.0.9 pyperclip==1.9.0 PyRect==0.2.0 PyScreeze==1.0.1 pytweening==1.2.0 pywin32==306 |
※ pip install pywin32 psutil pyautogui pyperclip