Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Python Selenium - Open new tab / focus tab / close tab

On a recent project, I ran into an issue with Python Selenium webdriver. There's no easy way to open a new tab, grab whatever you need and return to original window opener.

Here's a couple people who ran into the same complication:

So, after many minutes (read about an hour) of searching, I decided to do find a quick solution to this problem.

First thing, I've broken down all the steps that were required to do by my program:

  1. Open a new window/tab by simulating a click on a link
  2. Add focus on this new tab
  3. Wait for an element on the new page to be rendered (ui.WebDriverWait)
  4. Do whatever I have to do on this new page
  5. Close the tab
  6. Return focus on original window opener

Easy solution

  • First off, we import our packages:

    import selenium.webdriver as webdriver
    import selenium.webdriver.support.ui as ui
    from selenium.webdriver.common.keys import Keys
    from time import sleep    
  • Let's do it:

    browser = webdriver.Firefox()
    browser.get('https://www.google.com?q=python#q=python')
    first_result = ui.WebDriverWait(browser, 15).until(lambda browser: browser.find_element_by_class_name('rc'))
    first_link = first_result.find_element_by_tag_name('a')
    
    # Save the window opener (current window, do not mistaken with tab... not the same)
    main_window = browser.current_window_handle
    
    # Open the link in a new tab by sending key strokes on the element
    # Use: Keys.CONTROL + Keys.SHIFT + Keys.RETURN to open tab on top of the stack 
    first_link.send_keys(Keys.CONTROL + Keys.RETURN)
    
    # Switch tab to the new tab, which we will assume is the next one on the right
    browser.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.TAB)
        
    # Put focus on current window which will, in fact, put focus on the current visible tab
    browser.switch_to_window(main_window)
    
    # do whatever you have to do on this page, we will just got to sleep for now
    sleep(2)
    
    # Close current tab
    browser.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 'w')
    
    # Put focus on current window which will be the window opener
    browser.switch_to_window(main_window)

Simple!

@bsgreenb

This comment has been minimized.

Copy link

bsgreenb commented Jul 5, 2014

Make sure to update the commands for your OS. If you're on Mac use Keys.COMMAND in the right places

@Jakobovski

This comment has been minimized.

Copy link

Jakobovski commented Aug 24, 2014

On Mac I had to use something slightly different to switch between tabs:
browser.find_element_by_tag_name('body').send_keys(Keys.COMMAND + Keys.NUMPAD2)

I also did not need to use
browser.switch_to_window(main_window)

@lrhache

This comment has been minimized.

Copy link
Owner Author

lrhache commented Sep 4, 2014

Thanks for the input. I work on Ubuntu, so I guess we should expect the same behaviour on Windows.

@mineta

This comment has been minimized.

Copy link

mineta commented Nov 27, 2014

Thanks!
I was working on this all day and your post helped me a lot! :-)

@sojan-official

This comment has been minimized.

Copy link

sojan-official commented Dec 25, 2014

great help . thanks man

@typedt

This comment has been minimized.

Copy link

typedt commented Jan 19, 2015

I'm using Mac OSX with selenium with Chrome webdriver, tried to use
browser.find_element_by_tag_name('body').send_keys(Keys.COMMAND + Keys.NUMPAD2)
and
browser.find_element_by_tag_name('body').send_keys(Keys.COMMAND+ 't'),
but neither worked.
So I had to use
browser.execute_script('''window.open("about:blank", "_blank");''') which finally worked.

@starryknight64

This comment has been minimized.

Copy link

starryknight64 commented Apr 1, 2015

I had to do something a bit different as CTRL+W wasn't closing the tab:

curWindowHndl = browser.current_window_handle
elem.send_keys(Keys.CONTROL + Keys.ENTER) #open link in new tab keyboard shortcut
sleep(2) #wait until new tab finishes loading
browser.switch_to_window(browser.window_handles[1]) #assuming new tab is at index 1
browser.close() #closes new tab
browser.switch_to_window(curWindowHndl)
@lrhache

This comment has been minimized.

Copy link
Owner Author

lrhache commented Apr 6, 2015

Thanks @starryknight64, this snippet might need updates... it's two years old.

@erm3nda

This comment has been minimized.

Copy link

erm3nda commented Oct 25, 2015

Update url to "https://www.google.es/?gws_rd=ssl#safe=off&q=python" and will be fine

@Danielyan86

This comment has been minimized.

Copy link

Danielyan86 commented Jan 13, 2016

chrome doesn't work and no exception neither

@saikirankv

This comment has been minimized.

Copy link

saikirankv commented Jan 27, 2016

I'm using chromeDriver, I'm able to open a new tab but, I'm unable to pass the URL to newly opened tab.

@purvabansal

This comment has been minimized.

Copy link

purvabansal commented Mar 1, 2016

This thing doesnot work for phantomjs. Any suggestions on how to close and open a new tab in phantomjs using shortcut keys and selenium? For chrome, it worked fine in my case.

@niveditakhoche

This comment has been minimized.

Copy link

niveditakhoche commented Mar 14, 2016

Hi This is regarding selenium automation I am trying to switch between tabs using window handler could you tell me what am I doing wrong.

  1. go to Gmail

  2. open bing.com in next tab
    I am using browser.execute_script('''window.open("http://bings.com","_blank");''')
    to open new tab as Keys.COMMAND +’t’ is not working
    Also, for switching between windows I am trying to use window handler but could not get it work.Could you please let me know what am I doing wrong and what needs to be done thanks.
    browser = self.resource_handler.driver
    browser.set_page_load_timeout(60)
    browser.implicitly_wait(15)
    browser.get("http://google.com")
    main_window = browser.current_window_handle

    main_window = browser.getWindowHandle()

    print main_window

    time.sleep(5)

    browser.execute_script('''window.open("http://bings.com","_blank");''')

    time.sleep(2)

    second_window = browser.current_window_handle

    print browser.title

    ------------------------

    body = browser.find_element_by_tag_name("body").send_keys(Keys.COMMAND+Keys.TAB)

    browser.execute_script('''window.open("http://bings.com","_blank");''')

    browser.find_element_by_tag_name("body").send_keys(Keys.COMMAND + Keys.ENTER)

    time.sleep(5)
    print 'new oldtab opened'
    print browser.title
    browser.switch_to_window(main_window)
    print browser.switch_to_window(browser.window_handles[1])
    print 'newtab opened'
    time.sleep(5)

@vermontitude

This comment has been minimized.

Copy link

vermontitude commented Mar 21, 2016

On OS X using Chromebrowser, I've been able to open new tabs using:

send_keys(Keys.COMMAND + Keys.RETURN + "2")

And then switch to that tab using:

for handle in self.driver.window_handles:
    print "Handle is:" + str(handle) #only one handle number
    self.driver.switch_to_window(handle)

Instead of trying to physically switch to the tab using key commands, which didn't work, I realized that I could extract data from a tab as long as its window handle was selected. With the handle switched to the last tab opened, I generically extract data like so:

summary = self.driver.find_element(By.XPATH, '//body/div/div/div/section/section/div/section/p')
print summary.text

Then I close the tab like so:

self.driver.close()

Then switch back to the current window using the handle loop code from above:

for handle in self.driver.window_handles:
    print "Handle is:" + str(handle) #only one handle number
    self.driver.switch_to_window(handle)
@dandepeched

This comment has been minimized.

Copy link

dandepeched commented Oct 19, 2016

Currently this solution does not work for Firefox (tested on 47.0.1). Selenium does not see new Firefox tab as the new window and can't window_handle new tabs.
I was able to make it work by opening the link in a new window, not new tab. Following shortcut can be used for this:
Keys.SHIFT + Keys.RETURN

Here is modified code that I'm using:

browser = webdriver.Firefox()
browser.get('https://www.google.com?q=python#q=python')
first_result = ui.WebDriverWait(browser, 15).until(lambda browser: browser.find_element_by_class_name('rc'))
first_link = first_result.find_element_by_tag_name('a')

# Save the window opener (current window)
main_window = browser.current_window_handle

# Open the link in a new window by sending key strokes on the element
first_link.send_keys(Keys.SHIFT + Keys.RETURN)

# Get windows list and put focus on new window (which is on the 1st index in the list)
windows = browser.window_handles
browser.switch_to.window(windows[1])

# do whatever you have to do on this page, we will just got to sleep for now
sleep(2)

# Close current window
browser.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 'w')

# Put focus back on main window
browser.switch_to.window(main_window)
@roesler-stan

This comment has been minimized.

Copy link

roesler-stan commented Oct 21, 2016

This is great, thanks! However, I am having trouble reading the new tab's page source with browser.page_source. It keeps giving me the not-open tab on the left's source instead.

@nemxbg

This comment has been minimized.

Copy link

nemxbg commented Nov 29, 2016

@roesler-stan
To read new TAB u must handle it first:
browser.switch_to.window(browser.window_handles[-1])

window_handles[-1]

It handles THE LAST tab opened in browser because window_handles give us LIST and -1 in list take the last element
Than u can use : browser.page_source :)

@nemxbg

This comment has been minimized.

Copy link

nemxbg commented Nov 29, 2016

ui.WebDriverWait(browser, 15).until(lambda browser: browser.find_element_by_class_name('rc'))

What this do?

@icesri

This comment has been minimized.

Copy link

icesri commented Mar 31, 2017

Thanks!!! I am able to switch to the new tab and read page contents.
But Not able to close the second tab.
I have nearly 100 links on the first tab which would open on new tab and I want to close them.

@ankushpatial

This comment has been minimized.

Copy link

ankushpatial commented May 10, 2017

i am able to use some keys like tab
browser.find_element_by_tag_name('body').send_keys(Keys.TAB)
but not able to use like ctrl+p & ctrl+f
browser.find_element_by_tag_name('body').send_keys(Keys.CONTROL +'p')

@Sentinel-Prime

This comment has been minimized.

Copy link

Sentinel-Prime commented Jun 16, 2017

This is great. Somehow I can't read the new tab page_source to get information . It give me the first tab page_source. how ca I solve this problem?

@michaelbukachi

This comment has been minimized.

Copy link

michaelbukachi commented Jul 5, 2017

This is how I do it:

element.send_keys(Keys.CONTROL + Keys.RETURN)
driver.switch_to.window(self.driver.window_handles[1])
# do stuff
driver.close()
driver.switch_to.window(self.driver.window_handles[0])
@xia-mu

This comment has been minimized.

Copy link

xia-mu commented Oct 10, 2017

Confirmed that these work on MacOS:

Open link in a new tab:
link_element.send_keys(Keys.COMMAND + Keys.RETURN)

Switch between tabs:
driver.switch_to.window(self.driver.window_handles[1])
driver.switch_to.window(self.driver.window_handles[0])

@pbabvey

This comment has been minimized.

Copy link

pbabvey commented Mar 29, 2018

Very good!

@aaravgotra

This comment has been minimized.

Copy link

aaravgotra commented Jun 18, 2018

current_handle=self.driver.current_window_handle
print current_handle
for i in self.driver.window_handles:
if (current_handle!=i):
self.driver.switch_to_window(i)
print self.driver.current_window_handle
It works on all browser for both win and mac

@rakibulhaq

This comment has been minimized.

Copy link

rakibulhaq commented Apr 24, 2019

@xia-mu, thanks for your input it worked!

@sugatoray

This comment has been minimized.

Copy link

sugatoray commented Jun 27, 2019

Thank you @typedt

browser.execute_script('''window.open("about:blank", "_blank");''')

browser.execute_script('''window.open("about:blank", "_blank");''') ==> worked for me

@aleglez22

This comment has been minimized.

Copy link

aleglez22 commented Sep 20, 2019

browser.switch_to_window(browser.window_handles[1])

you saved my life thanks

@emmatovar27

This comment has been minimized.

Copy link

emmatovar27 commented Nov 13, 2019

    This works for me, on windows 10 and Firefox 70

    main_window= driver.current_window_handle
    #Open a new tab in blank
    driver.execute_script("window.open(''),'_blannk'")
    # Switch to the new window
    driver.switch_to.window(driver.window_handles[1])
    **#Change the url in the .get**
    driver.get("https://gist.github.com/lrhache/7686903")
    sleep(2)
    print("DO things")
    #Close Current Tab
    driver.close()
     #Focus to the main window
    driver.switch_to.window(main_window)
@freyesval

This comment has been minimized.

Copy link

freyesval commented Jan 9, 2020

    This works for me, on windows 10 and Firefox 70

    main_window= driver.current_window_handle
    #Open a new tab in blank
    driver.execute_script("window.open(''),'_blannk'")
    # Switch to the new window
    driver.switch_to.window(driver.window_handles[1])
    **#Change the url in the .get**
    driver.get("https://gist.github.com/lrhache/7686903")
    sleep(2)
    print("DO things")
    #Close Current Tab
    driver.close()
     #Focus to the main window
    driver.switch_to.window(main_window)

Thanks a loot!!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.