Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to open a new window on a browser using Selenium WebDriver for python?
We can open a new window on a browser with Selenium webdriver. There are multiple ways to achieve this. Selenium can execute commands in Javascript with the help of the execute_script() method which is one of the ways of opening a new window. Then we shall use switch_to.window() method to shift focus to a particular window at a time.
Syntax −
driver.execute_script("window.open('');")
Example
Code Implementation with execute_script() method.
from selenium import webdriver
urlA = "https://www.tutorialspoint.com/about/about_careers.htm"
urlB = "https://www.tutorialspoint.com/questions/index.php"
driver = webdriver.Chrome (executable_path="C:\chromedriver.exe")
# maximize with maximize_window()
driver.maximize_window()
driver.get(urlA)
print("Page Title of urlA : " + driver.title)
# open new window with execute_script()
driver.execute_script("window.open('');")
# switch to new window with switch_to.window()
driver.switch_to.window(driver.window_handles[1])
driver.get(urlB)
print("Page Title of urlB : " + driver.title)
# close window in focus
driver.close()
# switch back to old window with switch_to.window()
driver.switch_to.window(driver.window_handles[0])
print("Current Title: " + driver.title)
driver.close()
Output

We can also open a new window on a browser by invoking two driver sessions simultaneously.
Example
Code Implementation.
from selenium import webdriver urlA = "https://www.tutorialspoint.com/about/about_careers.htm" urlB = "https://www.tutorialspoint.com/questions/index.php" driver = webdriver.Chrome (executable_path="C:\chromedriver.exe") # opening another driver session s_driver = webdriver.Chrome (executable_path="C:\chromedriver.exe") # maximize with maximize_window() driver.maximize_window() s_driver.maximize_window() driver.get(urlA) s_driver.get(urlB) print(driver.title) print(s_driver.title) driver.quit()
Output

Advertisements