2

I'm very new to python and I'm trying to print the url of an open websitein Chrome. Here is what I could gather from this page and googeling a bit:

import win32gui, win32con
def getWindowText(hwnd):
   buf_size = 1 + win32gui.SendMessage(hwnd, win32con.WM_GETTEXTLENGTH, 0, 0)
   buf = win32gui.PyMakeBuffer(buf_size)
   win32gui.SendMessage(hwnd, win32con.WM_GETTEXT, buf_size, buf)
   return str(buf)
hwnd = win32gui.FindWindow(None, "Chrome_WidgetWin_1" )
omniboxHwnd = win32gui.FindWindowEx(hwnd, 0, 'Chrome_OmniboxView', None)

print(getWindowText(hwnd))

I get this as a result:

<memory at 0x00CA37A0>

I don't really know what goes wrong, whether he gets into the window and the way I try to print it is wrong or whether he just doesn't get into the window at all.

Thanks for the help

0xtuytuy
  • 1,494
  • 6
  • 26
  • 51
  • Does this answer your question? [Get Chrome tab URL in Python](https://stackoverflow.com/questions/52675506/get-chrome-tab-url-in-python) – skjerns Jan 26 '20 at 14:01

2 Answers2

0

Only through win32 can only get the information of the top-level application. If you want to get the information of each component located in the application, you can use UI Automation.

Python has a wrapper package Python-UIAutomation-for-Windows, and then you can get the browser's address bar url through the following code:

import uiautomation as auto


def get_browser_tab_url(browser: str):
    """
    Get browser tab url, browser must already open
    :param browser: Support 'Edge' 'Google Chrome' and other Chromium engine browsers
    :return: Current tab url
    """
    if browser.lower() == 'edge':
        addr_bar = auto.EditControl(AutomationId='addressEditBox')
    else:
        win = auto.PaneControl(Depth=1, ClassName='Chrome_WidgetWin_1', SubName=browser)
        temp = win.PaneControl(Depth=1, Name=browser).GetChildren()[1].GetChildren()[0]
        for bar in temp.GetChildren():
            last = bar.GetLastChildControl()
            if last and last.Name != '':
                break
        addr_bar = bar.GroupControl(Depth=1, Name='').EditControl()
    url = addr_bar.GetValuePattern().Value
    return url


print(get_browser_tab_url('Edge'))
print(get_browser_tab_url('Google Chrome'))
print(get_browser_tab_url('Cent Browser'))
bruce
  • 462
  • 6
  • 9
0

This should work:

import uiautomation as auto


control = auto.GetFocusedControl()
controlList = []
while control:
    controlList.insert(0, control)
    control = control.GetParentControl()
    
control = controlList[0 if len(controlList) == 1 else 1]
    
address_control = auto.FindControl(control, lambda c, d: 
                                            isinstance(c, auto.EditControl))

print('Current URL:')
print(address_control.GetValuePattern().Value)
macsunmood
  • 1
  • 1
  • 1
  • 1