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() }")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With