I have a script that opens a web page at regular intervals and performs some operations on it. This script is based on the selenium
library in Python.
When this script is run during a period when the computer is undisturbed and no other scripts are running either, everything works fine. The problem arises when there is either a user interacting with the computer, or another selenium-based script runs which also opens site or folders on the computer.
It is crucial for my script in question to be able to open the website in such a way that the window is placed in the foreground.
This is important because a series of opencv tasks are run on the opened sites, hence it is crucial that they show up on the screen and not hidden behind some other folder or browser. I've been struggling with this for weeks now. My current implementation with all my approaches:
import win32gui, win32con
from webdriver_manager.chrome import ChromeDriverManager
from selenium import webdriver
def minimize_current_window():
"""
Method to run just before the selenium driver opening the url. Goal is to minimize
everything that was opened so as to ensure that the selenium webdriver can open the
specified url in the foreground.
"""
Minimize = win32gui.GetForegroundWindow()
win32gui.ShowWindow(Minimize, win32con.SW_MINIMIZE)
def config_selenium():
options = webdriver.ChromeOptions()
options.add_argument("start-maximized")
desired = options.to_capabilities()
driver = webdriver.Chrome(options=options, executable_path=ChromeDriverManager().install(),
desired_capabilities=desired)
return driver
def force_foreground(driver):
driver.maximize_window()
driver.switch_to.window(driver.window_handles[0])
driver.switch_to.window(driver.current_window_handle)
minimize_current_window()
driver = config_selenium()
driver.get(url)
for i in range(100):
print(f"Forced foregrounding attempt #{i}.")
force_foreground(driver)
I intentionally replicated the site opening process in a way that during the opening, I was using the computer. As such, Windows by default opens the new Chrome browser window in the background. The last step of "forced foregrounding" does nothing but flashing the Chrome icon on the taskbar, so I know that selenium interacts with the browser - yet, my current implementation still doesn't succeed in bringing that window forward.