Feign focus in Selenium chrome browser

空扰寡人 提交于 2019-12-06 03:45:54

问题


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.


回答1:


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() }")


来源:https://stackoverflow.com/questions/29734701/feign-focus-in-selenium-chrome-browser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!