假装在Selenium Chrome浏览器中 [英] Feign focus in Selenium chrome browser
问题描述
我正在使用Selenium从网站上抓取数据.该网站需要窗口焦点才能显示我需要的某些元素.
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.
Check out the code on GitHub
收到window.onblur
事件时,网站背景颜色将变为黑色;收到window.onfocus
事件时,网站背景颜色将变为白色.
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.
推荐答案
由于页面通过window
对象中的onfocus
和onblur
回调获取焦点信息,因此您可以自己调用它们.
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)
当然,如果要使浏览器认为它始终处于聚焦状态,请使onblur
方法调用onfocus
方法:
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() }")
这篇关于假装在Selenium Chrome浏览器中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!