【问题标题】:Get url from chrome using python使用python从chrome获取url
【发布时间】:2015-03-23 09:29:59
【问题描述】:

我对 python 很陌生,我正在尝试在 Chrome 中打印一个开放网站的 url。以下是我可以从这个页面收集并用谷歌搜索的内容:

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))

我得到了这个结果:

<memory at 0x00CA37A0>

我真的不知道出了什么问题,他是否进入了窗口以及我尝试打印它的方式是否错误,或者他是否根本没有进入窗口。

感谢您的帮助

【问题讨论】:

标签: python google-chrome url


【解决方案1】:

只有通过win32才能获得顶级应用的信息。如果想获取应用中各个组件的信息,可以使用UI Automation

Python有一个wrapper包Python-UIAutomation-for-Windows,然后可以通过以下代码获取浏览器的地址栏url:

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'))

【讨论】:

    【解决方案2】:

    这应该可行:

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-10
      • 2020-01-13
      • 2011-10-19
      • 1970-01-01
      • 2020-11-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多