12

How can my Python script get the URL of the currently active Google Chrome tab in Windows? This has to be done without interrupting the user, so sending key strokes to copy/paste is not an option.

4

3 回答 3

18

First, you need to download and install pywin32. Import these modules in your script:

import win32gui
import win32con

If Google Chrome is the currently active window, first get the window handle by:

hwnd = win32gui.GetForegroundWindow()

(Otherwise, find the Google Chrome window handle by using win32gui.FindWindow. Windows Detective is handy when finding out class names for windows.)

It seems the only way to get the URL is to get the text in the "omnibox" (address bar). This is usually the tab's URL, but could also be any partial URL or search string that the user is currently typing.

Also, the URL in the omnibox won't include the "http://" prefix unless the user has typed it explicitly (and not yet pressed enter), but it will in fact include "https://" or "ftp://" if those protocols are used.

So, we find the omnibox child window inside the current Chrome window:

omniboxHwnd = win32gui.FindWindowEx(hwnd, 0, 'Chrome_OmniboxView', None)

This will of course break if the Google Chrome team decides to rename their window classes.

And then we get the "window text" of the omnibox, which doesn't seem to work with win32gui.GetWindowText for me. Good thing there's an alternative that does work:

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)

This little function sends the WM_GETTEXT message to the window and returns the window text (in this case, the text in the omnibox).

There you go!

于 2012-07-25T07:56:55.647 回答
4

克里斯蒂安的回答对我不起作用,因为 Chrome 的内部结构完全改变了,你不能再使用 win32gui 访问 Chrome 窗口的元素了。

我设法找到的唯一可能的方法是通过 UI 自动化 API,它有这个 python 包装器和一些使用示例

运行此命令并切换到您要从中获取地址的 Chrome 窗口:

from time import sleep
import uiautomation as automation

if __name__ == '__main__':
    sleep(3)
    control = automation.GetFocusedControl()
    controlList = []
    while control:
        controlList.insert(0, control)
        control = control.GetParentControl()
    if len(controlList) == 1:
        control = controlList[0]
    else:
        control = controlList[1]
    address_control = automation.FindControl(control, lambda c, d: isinstance(c, automation.EditControl) and "Address and search bar" in c.Name)
    print address_control.CurrentValue()
于 2017-06-04T09:06:20.343 回答
0

我对 StackOverFlow 很陌生,所以如果评论格格不入,我深表歉意。

看完之后:

  • 硒,
  • 直接启动 chrome://History,
  • 做一些键盘模拟:用 Pywinauto 复制/粘贴,
  • 根据 DevTool 的 Network 选项卡尝试使用 SOCK_RAW 连接来捕获标头(这个非常有趣),
  • 试图获取综合/搜索栏窗口元素的文本,
  • 关闭并重新打开 chrome 以读取历史记录表,....

当窗口标题(使用 hwnd + win32 检索)从“我的" 网址表。即使 sqlite db 被锁定并且不会干扰用户体验,也可以这样做。

非常基本的解决方案,需要:sqlite3、psutil、win32gui。希望有帮助。

于 2019-09-12T22:15:28.447 回答