Python:从 google chrome 获取活动选项卡 url

Python: Get active tab url from google chrome

我可以找到旧的答案,但是 none 他们为 python 3.9.10 和 Chrome 100.0.4896.88

工作

这是无效的代码之一。我们今天有什么办法可以做到这一点吗? 如果有人可以提供适用于 windows 10 os 的一般信息,欢迎。

from win32gui import GetForegroundWindow
from win32process import GetWindowThreadProcessId

from pywinauto.application import Application



window = GetForegroundWindow()
tid, pid = GetWindowThreadProcessId(window)
app = Application().connect(process=pid)
dlg = app.top_window()
title = "Address and search bar"
url = dlg.child_window(title=title, control_type="Edit").get_value()
print(url)

只要在time.sleep(3)结束前点击Chromewindow,下面的代码就可以工作了:

from win32gui import GetForegroundWindow
from win32process import GetWindowThreadProcessId
from pywinauto.application import Application
import time

time.sleep(3)
window = GetForegroundWindow()
tid, pid = GetWindowThreadProcessId(window)
app = Application(backend="uia").connect(process=pid, time_out=10)
dlg = app.top_window()
title = "Address and search bar"
url = dlg.child_window(title=title, control_type="Edit").get_value()
print(url)