Python:在OS X中激活窗口 [英] Python: Activate window in OS X
问题描述
我正在运行OS X 10.11
,并且已经使用Python
和Selenium
创建了一个Web抓取工具.刮板使用Firefox
作为浏览器来收集数据.
I'm running OS X 10.11
, and I have created a web scraper using Python
and Selenium
. The scraper uses Firefox
as the browser to collect data.
Firefox窗口必须在所有关键步骤保持活动状态,刮板才能正常工作.
The Firefox window must remain active at all critical steps, for the scraper to work.
当我离开使用Firefox作为活动窗口的计算机时,当我返回时,我经常发现活动窗口的焦点已更改为其他内容.一些过程正在窃取窗口焦点.
When I leave the computer with Firefox as the active window, when I return I often find that the active window focus has changed to something else. Some process is stealing the window focus.
是否可以通过编程方式告诉操作系统激活Firefox窗口?如果是这样,我可以告诉脚本在执行脚本中的每个关键操作之前先执行此操作.
Is there a way that I can programatically tell the OS to activate the Firefox window? If so, I can tell the script to do that before every critical action in the script.
最好,这是我想使用Python实现的.但是启动辅助AppleScript
来完成此特定任务也可能是解决方案.
Preferably, this is something that I would like to achieve using Python. But launching a secondary AppleScript
to do this specific task may also be a solution.
注意: Atm,我不是想重写脚本来使用无头浏览器,而只是通过强制激活窗口来使其正常工作.
Note: Atm, I'm not looking at rewriting my script to use a headless browser – just to make it work by forcing active window.
推荐答案
您可以在python中使用AppleEvents导入模块Carbon
.这是一个通过脚本脚本标识符激活FireFox的python脚本示例.
You can use AppleEvents in python importing the module Carbon
. Here an example of an python script activating FireFox by its bundle identifier.
from Carbon import AppleEvents
from Carbon import AE
target = AE.AECreateDesc(AppleEvents.typeApplicationBundleID, "org.mozilla.FireFox")
activateEvent = AE.AECreateAppleEvent( 'misc', 'actv', target, AppleEvents.kAutoGenerateReturnID, AppleEvents.kAnyTransactionID)
activateEvent.AESend(AppleEvents.kAEWaitReply, AppleEvents.kAENormalPriority, AppleEvents.kAEDefaultTimeout)
这篇关于Python:在OS X中激活窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!