Python: Activate window in OS X

不打扰是莪最后的温柔 提交于 2020-07-19 11:07:12

问题


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.

The Firefox window must remain active at all critical steps, for the scraper to work.

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.

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.

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.

Note: Atm, I'm not looking at rewriting my script to use a headless browser – just to make it work by forcing active window.


回答1:


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)



回答2:


tell application "Firefox" to activate

is the way to do it in AppleScript



来源:https://stackoverflow.com/questions/34705575/python-activate-window-in-os-x

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