├── README.md └── lambdatest.py /README.md: -------------------------------------------------------------------------------- 1 | ## How to handle multiple tabs in automation test in Python-selenium on [LambdaTest](https://www.lambdatest.com/?utm_source=github&utm_medium=repo&utm_campaign=Python-selenium-multiple-tabs) 2 | 3 | If you want to handle multiple tabs using an automation test in Python-selenium on LambdaTest, you can use the follwing steps. You can refer to sample test repo [here](https://github.com/LambdaTest/python-selenium-sample). 4 | 5 | ### Code 6 | 7 | To open a new tab, you can use the following line of code: 8 | 9 | ```python 10 | driver.execute_script("window.open('about:blank','secondtab');") 11 | ``` 12 | 13 | To switch to the new tab, you can use the following line of code: 14 | 15 | ```python 16 | #by using tab name 17 | driver.switch_to.window("secondtab") 18 | ``` 19 | or 20 | ```python 21 | #by using tab id 22 | driver.switch_to.window("2") 23 | ``` 24 | 25 | ## Run your test 26 | 27 | ```bash 28 | python lambdatest.py 29 | ``` 30 | 31 | # Links: 32 | 33 | [LambdaTest Community](http://community.lambdatest.com/) 34 | 35 | -------------------------------------------------------------------------------- /lambdatest.py: -------------------------------------------------------------------------------- 1 | import os 2 | import unittest 3 | import sys 4 | from selenium import webdriver 5 | 6 | username = os.environ.get("LT_USERNAME") 7 | access_key = os.environ.get("LT_ACCESS_KEY") 8 | 9 | 10 | class FirstSampleTest(unittest.TestCase): 11 | 12 | # setUp runs before each test case 13 | def setUp(self): 14 | desired_caps = { 15 | 'LT:Options': { 16 | "user": username, 17 | "accessKey": access_key, 18 | "build": "UnitTest-Selenium-Sample", 19 | "name": "UnitTest-Selenium-Test", 20 | "platformName": "Windows 11", 21 | "selenium_version": "4.0.0" 22 | }, 23 | "browserName": "Chrome", 24 | "browserVersion": "latest", 25 | } 26 | 27 | self.driver = webdriver.Remote( 28 | command_executor="http://hub.lambdatest.com:80/wd/hub", 29 | desired_capabilities=desired_caps) 30 | 31 | 32 | # tearDown runs after each test case 33 | 34 | def tearDown(self): 35 | self.driver.quit() 36 | 37 | def test_tabs(): 38 | """ 39 | Create new tab, switch to it and switch back to old tab 40 | :return: None 41 | """ 42 | driver.get('https://www.lambdatest.com/') 43 | driver.maximize_window() 44 | driver.execute_script("window.open('about:blank','secondtab');") 45 | driver.switch_to.window("secondtab") 46 | driver.get('https://www.lambdatest.com/') 47 | driver.switch_to.window(1) 48 | assert success == True 49 | 50 | if __name__ == "__main__": 51 | 52 | #run testcases 53 | unittest.main() 54 | --------------------------------------------------------------------------------