2

I'm using Python and the selenium webdriver to run PhantomJS.

from selenium import webdriver b = webdriver.PhantomJS()

I would like for the PhantomJS shell to automatically be hidden as soon as it starts up. I mistakenly assumed that you might be able to do this via b.set_window_position() or b.set_window_size(), but it seems these adjust settings of the headless browser, which isn't visible anyway. Is there any way to hide the window?

Sam Krygsheld
  • 2,060
  • 1
  • 11
  • 18

1 Answers1

1

I found a solution! As far as I know, what I was asking is not possible using the webdriver like it is for other browsers. However, you can use other modules to look through the names of windows that are present and then minimize them based on name.

import win32gui, win32con

toplist = []
winlist = []

def enum_callback(hwnd, results):
    winlist.append((hwnd, win32gui.GetWindowText(hwnd)))

(CODE THAT BRINGS UP THE PHANTOMJS WINDOW)

win32gui.EnumWindows(enum_callback, toplist)
phantom = [(hwnd, title) for hwnd, title in winlist if 'phantom' in title.lower()]
phantom = phantom[0]
win32gui.ShowWindow(phantom[0], win32con.SW_MINIMIZE)

Credit for this answer goes to ars.

Sam Krygsheld
  • 2,060
  • 1
  • 11
  • 18
  • Thank you, I was struggling with this a bit. Is this still the best way to do so? – Moondra Oct 10 '18 at 21:33
  • 1
    As far as I know, yes. The only change I might make is to create a list of existing windows before and after loading PhantomJS so that you can figure out which windows are new (good for if you will have multiple PhantomJS windows). – Sam Krygsheld Oct 18 '18 at 20:07