Skip to content

Instantly share code, notes, and snippets.

Last active June 10, 2023 13:49
Show Gist options
  • Save lrhache/7686903 to your computer and use it in GitHub Desktop.
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 as ui
    from selenium.webdriver.common.keys import Keys
    from time import sleep    
  • Let's do it:

    browser = webdriver.Firefox()
    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
    # do whatever you have to do on this page, we will just got to sleep for now
    # 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


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
        # Switch to the new window
        #Change the url in the .get
        print("DO things")
        #Close Current Tab
         #Focus to the main window

Thanks Bro!! <3

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