如何在 Windows 中获取活动的 Google Chrome 选项卡的 URL? [英] How do I get the URL of the active Google Chrome tab in Windows?

查看:43
本文介绍了如何在 Windows 中获取活动的 Google Chrome 选项卡的 URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 Python 脚本如何获取 Windows 中当前活动的 Google Chrome 选项卡的 URL?这必须在不打扰用户的情况下完成,因此发送按键进行复制/粘贴不是一种选择.

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.

推荐答案

首先需要下载安装pywin32.在您的脚本中导入这些模块:

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

(否则,使用 win32gui.FindWindow 查找 Google Chrome 窗口句柄.Windows Detective 在查找 Windows 的类名时很方便.)

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

似乎获取 URL 的唯一方法是获取 多功能框"(地址栏).这通常是选项卡的 URL,但也可以是用户当前输入的任何部分 URL 或搜索字符串.

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.

此外,多功能框中的 URL 不会包含http://"前缀,除非用户明确输入(并且尚未按下 Enter 键),但实际上它会包含https://"或如果使用这些协议,则为ftp://".

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.

因此,我们在当前 Chrome 窗口中找到了多功能框子窗口:

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

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

如果 Google Chrome 团队决定重命名他们的窗口类,这当然会中断.

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

然后我们得到多功能框的窗口文本",它似乎不适用于 win32gui.GetWindowText 对我来说.好在有一个可行的替代方案:

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)

这个小函数发送WM_GETTEXT 消息到窗口并返回窗口文本(在本例中为多功能框中的文本).

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

你去吧!

这篇关于如何在 Windows 中获取活动的 Google Chrome 选项卡的 URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆