Home > Enterprise >  Python: Get active tab url from google chrome
Python: Get active tab url from google chrome

Time:04-15

I could find old answers but none of them working for python 3.9.10 and Chrome 100.0.4896.88

This is one of the code that is not working. Is there any way we can do that today? If anyone can give generic information that applies to windows 10 os, its welcome.

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)

CodePudding user response:

The following code works as long as you click on the Chrome window before the end of the time.sleep(3) :

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