Many times we thought why selenium doesn’t have options to open new tab or window through code. Now, the wait is over. This feature is added in Selenium 4. Lets see how to work on it!!
Versions used while doing this blog post, (These are the prerequisites to automate chrome browser. Browser and driver versions should match)
selenium python version – 4.5.0
chrome browser version – 105
chrome driver version – 105 (Download link : https://chromedriver.chromium.org/downloads) [download this to a path in project directory]
Chrome browser can be opened using selenium by following below steps:
1. Instantiate (creation of object) driver object with webdriver.Chrome() (This step opens the chrome browser)
driver = webdriver.Chrome("chromedriver path need to be passed")
2. Now, next steps of maximizing the browser, setting implicit timeout for driver object and launch of expected URL can be carried out in default window
driver.implicitly_wait(10)
driver.maximize_window()
driver.get("https://www.google.com")
print("Page title -> "+driver.title)
3. Now, lets open a new tab and open another URL in it
driver.switch_to.new_window('tab')
driver.get("https://crazyautomator.com/find-elements-with-relative-locator-strategy-using-selenium-4-and-java/")
print("Page title of new tab -> "+driver.title)
4. Now, lets open a new window and open another URL in it
driver.switch_to.new_window('window')
driver.get("https://crazyautomator.com/read-server-client-logcat-logs-using-appium-and-java/")
print("Page title of new window -> "+driver.title)
5. Quit/close the driver object after automating the necessary flows within the website.
driver.quit()
Sample code for reference
from selenium import webdriver
driver = webdriver.Chrome("chromedriver path to be passed")
driver.implicitly_wait(10)
driver.maximize_window()
driver.get("https://www.google.com")
print("Page title -> "+driver.title)
driver.switch_to.new_window('tab')
driver.get("https://crazyautomator.com/find-elements-with-relative-locator-strategy-using-selenium-4-and-java/")
print("Page title of new tab -> "+driver.title)
driver.switch_to.new_window('window')
driver.get("https://crazyautomator.com/read-server-client-logcat-logs-using-appium-and-java/")
print("Page title of new window -> "+driver.title)
driver.quit()