gpt4 book ai didi

python - 在 Python 中获取 Chrome 标签 URL

转载 作者:行者123 更新时间:2023-12-03 15:36:16 25 4
gpt4 key购买 nike

我想获取有关我的 Chrome 选项卡的信息,例如当前选项卡的 URL 或自动获取所有 URL,但我找不到任何有关它的文档。我安装了 Chrome API,但我所看到的没有类似的东西。谢谢你的帮助

最佳答案

不用担心本地语言解决方案和对 Chrome、Firefox、Edge、Opera 和其他大多数 Chrome 引擎浏览器的支持:

Support to modify current tab url, other browsers can add their own adaptations if they are not available, and more functions supported by UIAutomation can be customized.

import uiautomation as auto


class BrowserWindow:
def __init__(self, browser_name, window_index=1):
"""
A Browser Window support UIAutomation.

:param browser_name: Browser name, support 'Google Chrome', 'Firefox', 'Edge', 'Opera', etc.
:param window_index: Count from back to front, default value 1 represents the most recently created window.
"""
if browser_name == 'Firefox':
addr_bar = auto.Control(Depth=1, ClassName='MozillaWindowClass', foundIndex=window_index) \
.ToolBarControl(AutomationId='nav-bar').ComboBoxControl(Depth=1, foundIndex=1) \
.EditControl(Depth=1, foundIndex=1)
else:
win = auto.Control(Depth=1, ClassName='Chrome_WidgetWin_1', SubName=browser_name, foundIndex=window_index)
win_pane = win.PaneControl(Depth=1, Compare=lambda control, _depth: control.Name != '')
if browser_name == 'Edge':
addr_pane = win_pane.PaneControl(Depth=1, foundIndex=1).PaneControl(Depth=1, foundIndex=2) \
.PaneControl(Depth=1, foundIndex=1).ToolBarControl(Depth=1, foundIndex=1)
elif browser_name == 'Opera':
addr_pane = win_pane.GroupControl(Depth=1, foundIndex=1).PaneControl(Depth=1, foundIndex=1) \
.PaneControl(Depth=1, foundIndex=2).GroupControl(Depth=1, foundIndex=1) \
.GroupControl(Depth=1, foundIndex=1).ToolBarControl(Depth=1, foundIndex=1) \
.EditControl(Depth=1, foundIndex=1)
else:
addr_pane = win_pane.PaneControl(Depth=1, foundIndex=2).PaneControl(Depth=1, foundIndex=1) \
.PaneControl(Depth=1, Compare=lambda control, _depth:
control.GetFirstChildControl() and control.GetFirstChildControl().ControlTypeName == 'ButtonControl')
addr_bar = addr_pane.GroupControl(Depth=1, foundIndex=1).EditControl(Depth=1)
assert addr_bar is not None
self.addr_bar = addr_bar

@property
def current_tab_url(self):
"""Get current tab url."""
return self.addr_bar.GetValuePattern().Value

@current_tab_url.setter
def current_tab_url(self, value: str):
"""Set current tab url."""
self.addr_bar.GetValuePattern().SetValue(value)


browser = BrowserWindow('Google Chrome')

print(browser.current_tab_url)
browser.current_tab_url = 'www.google.com'
print(browser.current_tab_url)
pywinauto 和 uiautomation 背后的原理都是 Windows UI Automation .
Pywinauto 搜索控制对我来说太慢了,因为它需要搜索所有子树。
如果想要更快的速度,自定义搜索位置访问UI可能会更快,uiautomation是一个包装包 Python-UIAutomation-for-Windows .
上面代码测试第一次获取速度在0.1s以内,平均0.05s,基于缓存重新获取会更快。

关于python - 在 Python 中获取 Chrome 标签 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52675506/

25 4 0