How To Switch Tabs In A Browser Using Selenium Python?

Nishant Choudhary

Posted On: December 23, 2020

view count153298 Views

Read time17 Min Read

This article is a part of our Content Hub. For more in-depth resources, check out our content hub on Selenium Python Tutorial.

Selenium automation offers dexterous ways to perform day-to-day tasks most efficiently. From capturing screenshots to testing PDF files, there’s no limit to what you can do with Selenium automation. Developers and testers are masters of drilling websites and finding loopholes. More often than not, this drill involves switching tabs multiple times a day. To reduce the manual effort that goes into doing so, we recommend using Python Selenium to switch tabs.

In this article, we will help you master multiple ways to switch tabs in Selenium using Python. If you are preparing for an interview you can learn more through Selenium interview questions.

Let’s get started –

When Do We Need To Open Or Switch Tabs In Selenium Automation?

Opening a new tab or switching between multiple tabs is one of the most basic functions performed by all of us every single day. Let us look into some scenarios when opening or switching tabs comes in handy during Selenium automation.

App Suits – Testing Features That Can Work Parallely

The most obvious scenario is when your application is too big and has mini-applications within it. For example, if you have used Linkedin, you might have come across ‘Linkedin Learning’ & ‘Linkedin Sales Navigator’ as two sub-applications. Similarly, many other applications are composed of several other smaller constituent applications. For example, G-suite, Youtube (media player & creator studio), Hubspot, Azure & Amazon, etc., some of these, by default, open up in a new tab. For others, it makes sense to intentionally open a new application in a new tab. This is where Selenium automation testing comes in.

Testing Ecommerce App Features

Let’s take another example of e-commerce application testing. Suppose you are testing an e-commerce website and you want to add a product to the cart. Then, you want to check if it gets reflected on the cart page. Next, you want to add another product to the cart. And then you want to confirm if it is visible in the cart. Doing this in the same browser window and tab could be a tenacious & time-taking task, and that’s where Selenium automation comes in.

Multimedia Uploading Functionality Testing

Another common example could be of uploading multiple videos parallelly to a vlogging platform like Vimeo or Youtube. This is an ideal case for multi-browser, cross-tab testing.

In short, automation testing involves switching tabs in the following scenarios –

  • Testing parallel features of large applications. E.g., Zoho, G-suite, Office365, etc.
  • Testing links that automatically open in a new tab. E.g. – eCommerce applications
  • Parallel testing of independent applications if the need arises.

In this Python Selenium switch tabs tutorial, we will be focusing on opening and switching between the tabs using Python & Selenium. We have dedicated articles for on-page testing operations like handling alerts, drag and drop objects using a mouse, or taking full-page screenshots. You may want to refer to those to dive deeper into Selenium automation use cases.

This certification is for professionals looking to develop advanced, hands-on expertise in Selenium automation testing with Python and take their career to the next level.

Here’s a short glimpse of the Selenium Python 101 certification from LambdaTest:

How To Create A New Tab In Selenium Python?

In order to get started with Python Selenium switch tabs automation, your system needs to be equipped with the required tools. Here are all the prerequisites:

  • You have the latest Selenium-Python bindings, Python3, pip, virtualenv installed in your system
  • You also have a path to the executable WebDriver of your browser choice in your system.

If not, you can simply follow the instructions given in this Selenium 4 with Python blog to get started with Python Selenium switch tab automation. We can open new tabs in Selenium-Python by executing JavaScript as well as by using Selenium’s ActionChains class.

Let’s see how this can be done.

Open New Tabs In Selenium By Executing JavaScript

In the following code, replace “chrome_webdriver_executable_path” with the path to your chrome executable. Ideally, you should add it in your systems PATH variable.

Sample Code 1-

execute_script is a method provided by Selenium to execute JavaScript snippets inside the remotely controlled browser. It could be used to scroll the webpage, open a new window, fire-up an alert, and a lot more. window.open is a DOM method to launch new tabs. It accepts URL, name, specs and replaces them as parameters. For our Selenium automation testing use-case, we’re only concerned with the URL & name. You may use specs to launch new tabs in different sizes and configurations.

In “Sample Code 1”, if you want to open a blank tab in Selenium Python, then replace the line after the comment with the following code –

Or another equivalent would be –

As “_blank” is the default value for the optional “name” parameter. “_parent”, “_self”, “_top” are some other values it can take to open the “url” in the parent frame, same window, or top frame, respectively.

Open New Tabs In Selenium By Executing ActionChains Class

The second way to launch a new tab in Selenium is to use the key_up and key_down method of Selenium’s ActionChains class and click on an HTML element with a link.

Sample Code 2-

ActionChains class of selenium grid enables low-level interactions with the web application elements. Selenium automation testers often use it to move the mouse cursor, double-clicking an HTML element, dragging and dropping operations, and of course, to press keyboard keys. Key_down method of ActionChains imitates pressing a key passed as a parameter. The Key_up method releases the pressed key. Again, the key is passed as the parameter to the key_up method.

Open New Tabs In Selenium By Executing send_keys

Another way to open new tabs in Selenium is by using send_keys to the “body” element. This is the syntax used-

Note: You’ll find a lot of solutions on the web claiming – ‘This is identical to pressing Ctrl & ‘t’ key together on user-controlled browsers.’ or ‘This method fires up a new tab on the element in focus.’ If you have to open a link in a new tab, get the location of an element using XPath or CSS selectors and nest send_keys operation on it with Keys.CONTROL + ‘t’ as parameters. But sadly, this doesn’t work. We checked with the latest Selenium & Python version on the date of publishing this article.

Cta Python

How To Switch Tabs In Selenium Python?

Switching tabs in selenium python is not that cumbersome. We can use the current_window_handle & window_handles method of Selenium WebDriver to automate tab switching in the Selenium Grid using Python. Besides, we can also use ActionChains class to switch tabs in remotely controlled cross-browser automation testing.

Switch Tabs In Selenium Python By Executing switch_to_window, switch_to.window, current_window_handle & window_handles

In this Selenium Python switch tab tutorial, we can get started by using several methods, including switch_to_window, switch_to.window, current_window_handle & window_handles. Before we jump off to the execution, you must note that the switch_to_window method is now deprecated, and the switch_to.window method has replaced it.

Code Breakdown-

Let us break down the code for better clarity on Selenium Python switch tab automation. Here it goes-

Here, we first import all the required dependent libraries. Python’s unittest module to write test cases in Python. WebDriver module from the python-selenium library to automate browser actions. And ActionChains class from Selenium WebDriver – to automate low-level interactions using mouse and keyboard interrupts. Python time module to implicitly or explicitly pause the execution or wait. Lastly, the Keys module from Selenium WebDriver to imitate keyboard button inputs.

This is to set up your testing browser environment. If you’re using a cloud automation testing platform like LambdaTest, for that too, ideally, you have to configure settings in this function. Here we are using Chrome as our browser, but you may use any browser. The script works exactly the same with Firefox or Edge too.

Next, we define a function “test_switch_tab”. Ideally, if you’re using a unittest library, start this function name with “test”. driver.maximize_window fires up Chrome instance in full-screen mode.

First line loads the LamdaTest homepage in our recently launched Chrome instance. time.sleep(sec) pauses the program from executing the next lines for specified seconds.

LamdaTest homepage

We use the current_window_handle method of the driver to get & store the handle id for the active tab in a variable named first_tab_handle.

On LamdaTest’s homepage, we find a link to the selenium-automation page using XPath.

Next, we instantiate ActionChains and perform key_down, click, and key_up chained operations to open the LambdaTest’s selenium-automation webpage in a new tab. We’ll skip explaining the next few self-explanatory code lines that demonstrate that the driver control remains with the first tab by inquiring about the driver’s current_window_handle method.

Here, we use the switch_to.window method and pass it the handle id of the new tab launched using ActionChains class as an argument. This switched driver control to the tab with selenium-automation LamdaTest’s webpage.

This line launches a new tab. It does get highlighted, but the control is still with the selenium-automation tab.

The above lines logically retrieve the handle id for JS triggered new tab and stores it in js_tab_handle.

This line switches to the latest tab.

We can also switch between tabs using window_handles indexes, negative index counts in reverse order from the last tab.

coding jag

selenium python tutorial

But it is a good idea to store ids in variables and switch tabs using variables just like the below line of code.

This function gets automatically called after the test case gets executed and it shuts the driver.

Output-

On successful execution of the above script, you shall see the following output –

successful execution

How To Switch Between iFrames In Selenium Python?

Switching between iFrames is similar to switching between tabs. The difference is in syntax. Here, we have to use switch_to.frame()

We can switch between iFrames by locating the element using XPath or CSS Selectors, and we can also switch using the iFrame index.

To transfer driver control back to default content, use switch_to.default_content()

You can also refer to the below video tutorial on how to handle Windows and Frames in selenium.

Switch Tabs Using Selenium Automation On LambdaTest Cloud

Using a cloud-based platform is the best way to leverage Selenium automation and get the desired results seamlessly. You can perform Python Selenium switch tab automation on LamdaTest’s cloud Selenium Grid to make the most of it.

To do so, you can obtain the value for username, access token, and gridUrl upon registering with LambdaTest. You can register here for creating a LambdaTest account for free. Once you have the required information, you will need to declare your testing environment’s desired capabilities. LambdaTest’s Desired Capabilities Generator will provide you with the capabilities based on your choice of OS, browser & its version, resolution.

Execution-

This is the only function that needs to change when executing your script in the LamdaTest’s cloud Selenium Grid.

Conclusion

Cloud automation testing engineers get the flexibility and agility to uninhibitedly unleash their functional, acceptance, white-box, black-box, and regression testing drills on target web & mobile applications. While they do all this, switching between tabs might take up a lot of time. If you want to take your automation skills to the next level, start automating with Python Selenium switch tab automation and save a lot of manual effort.

Additionally, we recommend leveraging LambdaTest’s cloud-based platform is easy and cost-effective. With 3000+ operating systems & browsers to offer, there’s so much you can do with LambdaTest automation.

Happy Testing!

Frequently Asked Questions

How do I switch between tabs in Selenium?

You can use the current_window_handle & window_handles method of Selenium WebDriver to automate tab switching in the Selenium Grid using Python. Besides, you can also use ActionChains class to switch tabs in remotely controlled cross-browser automation testing.

How does Python handle multiple tabs in Selenium?

The best approach to handle multiple tabs is by using a Robot class or using JavascriptExecutor. Robot class ensures your tab is opened using the ‘Control + t’ command, while through a JavaScript executor, you can simply open the tab using windows.open. Post opening the tab, you can switch to the tab using either the Action Class approach or using Selenium WebDriver interface methods getWindowHandle & getWindowHandles.

For more information, you should read Handling Multiple Browser Tabs With Selenium.

How do I switch between windows in Python?

Use the current_window_handle & window_handles method of Selenium WebDriver to automate window switching in a Selenium Grid using Python. Furthermore, use the switch_to_window() method to switch to a particular window.

Can we use Selenium with Python?

Though the choice for the best programming language for Selenium test automation is highly subjective, Python is by far the best scripting language for test automation. It is easy to get started with Python test automation, and its wide range of test frameworks can be used for unit testing, cross browser testing, and more.

To learn more, please refer to Why Python Is My Favourite For Test Automation?

Why are broken links bad?

They can hurt the user experience – When users click on links and reach dead-end 404 errors, they get frustrated and may never return. They devalue your SEO efforts – Broken links restrict the flow of link equity throughout your site, impacting rankings negatively.

Is Python 3.11 stable?

Yes, The final, stable was released on October 3, 2022, following three additional beta versions and two candidate versions before that date.

how to switch python version?

To switch Python versions:

  • Install Multiple Versions: Install the desired Python versions side by side on your system.
  • Use Virtual Environments: Create virtual environments with specific Python versions using tools like virtualenv or conda.
  • Update System Path: Adjust the system PATH variable to point to the desired Python version’s executable.
  • Use Version Managers: Utilize version management tools like pyenv to easily switch between Python versions.
  • Command Prefix: Specify the desired Python version when running scripts, like using python3 instead of python.
  • Choose the method that best suits your needs and system setup.

    Is there a switch in Python?

    Python does not include a built-in switch statement. However, alternative approaches exist to replicate switch-like behavior for easier and faster programming. Python permits the creation of custom code snippets that mimic switch case functionality found in other languages.

    What does switch () do?

    The switch statement assesses whether a variable matches various predetermined values outlined in the test cases. Java, one of the most prevalent programming languages today, employs the switch statement for this purpose.

    Author Profile Author Profile Author Profile

    Author’s Profile

    Nishant Choudhary

    A Web Scraping Python Developer and Data Evangelist, Nishant also loves to evangelize startups and technologies by writing technical content.

    Blogs: 8



    linkedintwitter

    Test Your Web Or Mobile Apps On 3000+ Browsers

    Signup for free