Feign focus in Selenium chrome browser - python

I'm using Selenium to scrape data from a website. The website requires window focus in order to display certain elements that I need.
I want to be able to run my program in the background, without having to focus the window while it's running.
Is there any way to trick the site into thinking it's focused on?
I'm using the selenium chrome driver.
Edit: Here's a quick and dirty test I built.
Check out the code on GitHub
The website background color will turn black when the window.onblur event is recieved, and turn back white when the window.onfocus event is recieved.
I want to fake those events, to make the browser think it's recieved a focus event.

Since the page gets focus information through the onfocus and onblur callbacks in the window object, you can just call them yourself.
browser.execute_script("window.onfocus()")
browser.execute_script("window.onblur()")
For fun, try this script out:
from selenium import webdriver
import time
chromedriver = "./chromedriver"
browser = webdriver.Chrome(executable_path = chromedriver)
browser.get('http://anubiann00b.github.io/FocusTest/')
while True:
browser.execute_script("window.onfocus()")
time.sleep(1)
browser.execute_script("window.onblur()")
time.sleep(1)
And of course, if you want to make the browser think it's always focused, make the onblur method call the onfocus method:
browser.execute_script("window.onblur = function() { window.onfocus() }")

Related

How to stop selenium from switching to the window it's running on when it refreshes or does something on a webpage?

I want selenium to do everything in the background and play a sound when it reaches a specific page. But every time it refreshes or changes pages, it forcefully switches my current window to the browser its running in. How can I disable it? And if I can't, what's a good alternative to get what I'm trying to do.

Firefox browser wont open maximized and wont switch tabs using Selenium

I'm opening Firefox browser through selenium(3.141.0) on python 3.9, and it will always start minimized, even though in code I passed function .maximise_window() after opening the browser. When its started this way, it wont execute code to maximise and it wont execute code to switch tabs, and it wont even do it if im trying to switch tabs manually with my mouse.
If I immediately click on the initiated firefox browser on my taskbar when the program is started, it will function normally, but it will open my browsers home tab, and execute my code in new tab. Thats why you may see in code a part that closes that first tab. When i dont do it and when it starts "faulty", the home tab wont be opened.
Im also using the lenght of tabs as an indicator if the browser initiated faulty, where I tried to put it into loop and make it restart till it opens with 2 tabs, but it just wont unless I manually click it.
The only solution so far I can think of is kinda "hacky"...using pyautogui to scan my taskbar after initializing browser and clicking it fast, but I dont really like the idea.
The code goes through my company data warehouse site and manipulates it to download data.
Update
Other hacky solution I found is starting 2 browsers. First won't work, but second will. Meaning that browser works normally IF there is another Firefox browser open at the time.
Snippets of code:
from selenium import webdriver
import time
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
class DWH_browser:
def __init__(self):
self.browser = webdriver.Firefox()
self.browser.maximize_window()
self.browser.get("www.letskeepthecompanysiteasecret.org")
self.len_windows = len(self.browser.window_handles)
print(len(self.browser.window_handles))#this next part is used to close the extra tab when browser
#started normally and opens an extra tab
if len(self.browser.window_handles) == 2:
self.browser.switch_to.window(self.browser.window_handles[0])
self.browser.close()
self.browser.switch_to.window(self.browser.window_handles[0])
self.a = ActionChains(self.browser)
time.sleep(5)
DWH = DWH_browser()#and i initiate it in the code "normally"
#This was the other code I tried using to initate the browser and restart till its in 2 tabs, but not working
# issue_lenght = 1
# while issue_lenght == 1:
# DWH = DWH_browser()
# issue_lenght = DWH.len_windows
# if DWH.len_windows == 1:
# DWH.browser.quit()
# print("RESTARTING BROWSER")
Summarizing your issues:
Always start minimized.
Passed function maximise_window() after opening the browser.
Won't execute code to switch tabs.
To get rid of all these issues you need to ensure that:
Selenium is upgraded to current levels Version 4.4.0.
GeckoDriver is updated to current GeckoDriver v0.31.0 level.
Firefox Browser is updated to current firefox=103.0.2.
Additionally, you won't be needing self.browser.maximize_window() as firefox by default opens in a maximized mode.
Finally, trying to switch tabs manually with my mouse is a big no as the program execution may get interupted.

Can we get Selenium to focus on an open browser window?

I have been using Selenium for a couple of years now. I learned a ton, thanks to all the amazing people here at SO. Now, I just encountered a new challenge/opportunity. It seems like Selenium always wants to open a new window, which is a new instance, as far as I can tell, and this new instance doesn't know that I am already logged into the system that I want to be logged into. Normally I would run some generic code like this.
import time
from selenium.webdriver import ActionChains
from selenium import webdriver
driver = webdriver.Chrome('C:\\Users\\chromedriver.exe')
driver.get ('https://corp-login_place')
driver.find_element_by_id('USERID').send_keys('myid')
driver.find_element_by_id ('PASSWORD').send_keys('mypw')
list = [145, 270, 207]
for i in list:
driver.find_element_by_id('InputKeys_LOCATION').send_keys(i)
driver.find_element_by_class('PSPUSHBUTTON').click()
button = driver.find_element_by_class_name("Button")
button.click()
time.sleep(5)
So, I think that automation script should work, but when I run the code, it always opens a new browser window, and asks me to login. At this point my login credential don't work. Very weird. Anyway, I'm already logged in, and everything works fine if I just use the mouse and keyboard. It seems like the open browser window, which is out of focus, works fine, but Selenium don't focus on ths open window, and it opens a new window, which doesn't allow me to login.
For some reason, the code doesn't work when I hit F9, but if I run the process manually, using the mouse and keyboard, everything works totally fine. I feel like
Any insight or illumination, as to what is happening here, would be greatly appreciated. Thanks to all!
What I got is that you have a manually opened browser window (which was not opened with Selenium) and you want to control this window with Selenium?
Apparently this is not supported, but there is some code here that maybe can help you.
Selenium always uses a new instance of the browser no matter how many other browser windows are open in your system. If your problem is related to logging into the website you want to test, then please share the website url.
Or else if you are talking about attaching a session of browser window already opened in your system then this article (http://tarunlalwani.com/post/reusing-existing-browser-session-selenium/) might help, albeit the whole purpose of automating is compromised.

Python selenium code seems to wait after calling javascript that display modal dialog box

I'm using Python and Selenium to write an automation script in Internet Explorer.
When the web page throws up some kind of modal dialog box, the Python code stops running and just waits for some action to be taken on the popup. After you press the "yes" or "no" button, then the Python code continues.
I believe the underlying Javascript function that is getting called (saveClicked()) is generating the popup box using this line of code:
var result=window.showModalDialog('whatever....')
Does anyone know how to handle this in Selenium? I want my code to click "ok" in this window or to just accept it. I tried right-clicking on the window to look at source code, etc. but those options are not given to me...the only options are "move/close".
I've looked to see if there is some kind of default IE capability in Selenium that will just automatically accept all modal dialog boxes but haven't found any. I also thought of maybe wrapping the call to the Javascript function with something that would somehow send a keystroke to the alert. I'm open to anything!
Here is the code: It never moves past the .execute_script line...it just sits there waiting.
print('Saving')
# I have to do this because I can't get the handle to the save button
# using any of the known Selenium methods but calling the JS works
driver.execute_script('saveClicked();')
print('Test')
driver.switch_to().alert().send_keys(Keys.ENTER)
The code just STOPS after the Javascript is executed and never moves to the print('test') line or any other code I put there.
Any python selenium code suggestions to solve this would be greatly appreciated.
one way: you can try to use Alert to manage popups
Alert(driver).accept()
otherwise you can see the active window or tab with:
#get current window handle
p = driver.current_window_handle
#get windows
chwd = driver.window_handles
driver.switch_to.window(chwd[1])
reference:
https://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.common.alert
Try:
message = "saveClicked()" # or any other of your messages
driver.execute_script(f"alert(\"{message}\");")
driver.switch_to.alert.accept()

Python switch focus back to terminal from web browser with driver selenium

I am using selenium webdriver to open a webpage and fill out the form.
anyways In the middle of the code i need to provide input data in the terminal
but the focus still stays in the webbrowser, so i need to move mouse manulally back to the terminal.
is there anyway to switch focus back to terminal from the webbrowser?
sample code :
import time
from selenium import webdriver
driver = webdriver.Chrome() # Optional argument, if not specified will search path.
driver.get('https://www.seleniumeasy.com/test/basic-first-form-demo.html')
search_box = driver.find_element_by_id('user-message')
search_box.send_keys('John Rambo')
time.sleep(5) # Let the user actually see something!
test=input('please provide a number 0-9: \n') # I'd like the focus to switch back to the terminal
driver.quit()
Through Selenium - no. It's a library that communicates exclusively to a browser, through the WebDriver protocol. It can only send request to the browser, which may (or may not) execute them.
As such, it cannot communicate with anything outside it - the OS, and its app switching routines including.
For that you need some other library, that can either issue OS requests (switch app), or simulates keyboard/mouse inputs. But these are OS dependant, e.g. different ones for Windows, Mac or Linux.

Categories

Resources