chris chris - 2 months ago 8
Python Question

python selenium phantomJS new tab not working

I'm using selenium with the PhantomJS webdriver, and I've found that I cannot open a new tab using this webdriver. I'm using the standard line:

driver.find_element_by_tag_name('body').send_keys(Keys.COMMAND + 't')


I use a Mac.

I have also tried this with Firefox and it works.

Any help to get it working with PhantomJS would be appreciated!

Answer

I was having the same issue just now, and I found a way that is, in my opinion, better than attempting to send keys to PhantomJS.

Remember, PhantomJS is a headless browser - no actual window is rendered for your OS to access via keyboard shortcuts.

That being said, every time a new tab/window is opened, it is added to the driver's window handles. Each window handle has a unique identifier.

You can easily just switch to the ID of that window (and back to your original window handler - if you wish to).

Example:

# Click a link that opens a new tab ...

# You'll see there's a new window handle!
print(driver.window_handles)

# Switch to the new window handle in the window_handles list
driver.switch_to.window(driver.window_handles[1])

# Switch back to the original window
driver.switch_to.window(driver.window_handles[0])

Then it's trivial to just check the driver's current_url to ensure you are on the right page, i.e.:

assert "www.stackoverflow.com" in driver.current_url

This answer helped me: http://stackoverflow.com/a/29125205/295246

Comments