■ 메인 크롬 브라우저 활성 탭에서 URL을 구하는 방법을 보여준다.
▶ 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 78 79 80 81 |
import win32gui import win32process import psutil import requests from pywinauto import Application def findMainChromeBrowserWindowHandle(): chromeBrowserList = [] def enumerateWindowsCallback(windowHandle, _): if win32gui.IsWindowVisible(windowHandle) and win32gui.GetWindowText(windowHandle): _, processID = win32process.GetWindowThreadProcessId(windowHandle) try: process = psutil.Process(processID) if process.name().lower() == "chrome.exe": chromeBrowserList.append((windowHandle, process)) except psutil.NoSuchProcess: pass return True win32gui.EnumWindows(enumerateWindowsCallback, None) for windowHandle, process in chromeBrowserList: if not any("--type=" in arg for arg in process.cmdline()): return windowHandle return None def getChromeAddressBarText(): try: mainChromeBrowserWindowHandle = findMainChromeBrowserWindowHandle() if mainChromeBrowserWindowHandle is None: print("No main Chrome window found.") return None application = Application(backend="uia").connect(handle = mainChromeBrowserWindowHandle) window = application.window(handle = mainChromeBrowserWindowHandle) for className in ["OmniboxViewViews", "EditControl", "Edit"]: try: addressEdit = window.child_window(class_name=className) if addressEdit.exists(): return addressEdit.legacy_properties()["Value"] except Exception: continue print("Address bar element not found.") return None except Exception as exception: print(f"Error in getChromeAddressBarText : {str(exception)}") return None def addProtocolToUrl(url): if url.startswith("http://") or url.startswith("https://"): return url httpsURL = f"https://{url}" try: response = requests.head(httpsURL, allow_redirects = True, timeout = 5) if response.status_code == 200: return httpsURL except requests.RequestException: pass httpURL = f"http://{url}" try: response = requests.head(httpURL, allow_redirects = True, timeout = 5) if response.status_code == 200: return httpURL except requests.RequestException: pass return httpsURL def main(): addressBarText = getChromeAddressBarText() if addressBarText: fullURL = addProtocolToUrl(addressBarText) print(f"Chrome Address Bar Text (with protocol) : {fullURL}") else: print("Failed to get Chrome address bar text.") if __name__ == "__main__": main() """ Chrome Address Bar Text (with protocol) : https://icodebroker.com/archives/108379 """ |
▶ requirements.txt
1 2 3 4 5 6 7 8 9 10 11 12 |
certifi==2024.7.4 charset-normalizer==3.3.2 comtypes==1.4.6 idna==3.7 psutil==6.0.0 pywin32==306 pywinauto==0.6.8 requests==2.32.3 six==1.16.0 urllib3==2.2.2 |
※ pip install pywinauto pywin32 psutil requests 명령을 실행했다.