Skip to content

Instantly share code, notes, and snippets.

@lrhache
Last active June 10, 2023 13:49
Star You must be signed in to star a gist
Save lrhache/7686903 to your computer and use it in GitHub Desktop.
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!

@roesler-stan
Copy link

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
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
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
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
Copy link

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
Copy link

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
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-m
Copy link

xia-m 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
Copy link

pbabvey commented Mar 29, 2018

Very good!

@aaravgotra
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
Copy link

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

@sugatoray
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
Copy link

browser.switch_to_window(browser.window_handles[1])

you saved my life thanks

@emmatovar27
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
Copy link

    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!!!

Copy link

ghost commented Apr 2, 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)

THANK YOU!

@falgom4
Copy link

falgom4 commented May 23, 2020

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.

thanks!! This works on IE and Win7

driver.execute_script("window.open(''),'_blannk'")
driver.switch_to.window(driver.window_handles[1])
#do stuff
driver.switch_to.window(driver.window_handles[0])

@thevipinsaini
Copy link

    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)

Wonderful!
I am using windows 10 and chrome brower. Changing my code from this driver.execute_script("window.open('')") to this driver.execute_script("window.open(''),'_blank'") solved the problem.

@kwamena98
Copy link

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.

Thanks, it worked for me

@medelmaimouni
Copy link

Thanks man! it helped a lot, you saved my day

@hirios
Copy link

hirios commented Mar 8, 2021

    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 Bro!! <3

@dheeraj07
Copy link

dheeraj07 commented Apr 6, 2021

but

    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)

But this opens in a new window, any idea how to open in new tab?

@nikhilpatidar
Copy link

nikhilpatidar commented Jul 18, 2021

i want to do it in android what should i do ?????

@carevjr
Copy link

carevjr commented Sep 16, 2021

Amazing boys!! This is exactly what I was looking for!
Works smoothly on Windows 10 using Chrome tkss

    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 Bro!! <3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment