Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open and close new tab with Selenium WebDriver in OS X

I'm using the Firefox Webdriver in Python 2.7 on Windows to simulate opening (Ctrl+t) and closing (Ctrl + w) a new tab.

Here's my code:

from selenium import webdriver  
from selenium.webdriver.common.keys import Keys

browser = webdriver.Firefox()
browser.get('https://www.google.com')
main_window = browser.current_window_handle
# open new tab
browser.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't')
browser.get('https://www.yahoo.com')

# close tab
browser.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 'w')

How to achieve the same on a Mac? Based on this comment one should use browser.find_element_by_tag_name('body').send_keys(Keys.COMMAND + 't') to open a new tab but I don't have a Mac to test it and what about the equivalent of Ctrl-w?

Thanks!

like image 671
user2314737 Avatar asked Sep 20 '14 18:09

user2314737


People also ask

Which method can be used to close a new tab opened by WebDriver in Selenium?

close() and driver. quit() are two methods for closing a browser session in Selenium WebDriver. It is necessary to know when to use each method in a test script.

How do I switch between tabs in a browser using Selenium?

sendKeys(clickl); Then hold all the opened window ids in an ArrayList and shift the driver focus to the new tab with the switchTo method. Then pass the window id of the new tab as an argument to that method.

How does Selenium handle open a new window?

Open a New Tab await driver. get('https://selenium.dev'); // A new tab is opened and switches to it await driver. switchTo(). newWindow('tab'); // Loads Sauce Labs open source website in the newly opened window await driver.

How do I close the current tab in Selenium?

While doing stuff with selenium multiple browsers with multiple tabs will normally opens in order to close these tabs close() and quit() methods are used. close() method is used to close the current browser window on which the focus is set, on the other hand quit() method essentially calls the driver.


2 Answers

There's nothing easier and clearer than just running JavaScript.

Open new tab: driver.execute_script("window.open('');")

like image 86
Bek Avatar answered Sep 28 '22 08:09

Bek


open a new tab:

browser.get('http://www.google.com')

close a tab:

browser.close()

switch to a tab:

browser.swith_to_window(window_name)
like image 29
alien_frog Avatar answered Sep 28 '22 06:09

alien_frog