假装在Selenium Chrome浏览器中 [英] Feign focus in Selenium chrome browser

查看:516
本文介绍了假装在Selenium Chrome浏览器中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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.

这是我建立的一种快速而肮脏的测试.

在GitHub上查看代码

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对象中的onfocusonblur回调获取焦点信息,因此您可以自己调用它们.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆