The first method:
Usage Scenarios:
Multiple windows open, need to locate the newly opened window
Usage:
# Get handles to multiple open windows windows = driver.window_handles # Switch to the latest currently open window driver.switch_to.window(windows[-1])
Examples:
# _._ coding:utf-8 _._ """ :author: Flower Test :time: 2017.05.03 :content: switching browsers using the first method """ from selenium import webdriver import time # Open the home page of the Lesson Workshop website [first window]. driver = () ('/') driver.maximize_window() # Click on All Courses to go to the course library [second window]. driver.find_element_by_link_text('All Courses').click() (3) # Use the first method to switch browsers [switch to second window] windows = driver.window_handles driver.switch_to.window(windows[-1]) (3) # Click on a course in the course library to enter the course details screen [Click on an element in the second window page to determine whether the window is switched successfully]. driver.find_element_by_xpath('//*[@]/ul/li[2]').click() (3) # Close the browser () print('Test passed')
The second method:
Usage Scenarios:
Open two windows, need to locate the newly opened window
Usage:
# Get a handle to the first window opened window_1 = driver.current_window_handle # Get handles to all open windows windows = driver.window_handles # Switch to the newest window for current_window in windows: if current_window != window_1: driver.switch_to.window(current_window)
Examples:
# _._ coding:utf-8 _._ """ :author: Flower Test :time: 2017.05.03 :content: switching browsers using the second method """ from selenium import webdriver import time from selenium import webdriver import time # Open the home page of the Lesson Workshop website [first window]. driver = () ('/') driver.maximize_window() # Click on All Courses to go to the course library [second window]. driver.find_element_by_link_text('All Courses').click() (3) # Use the second method to switch browsers [switch to second window] window_1 = driver.current_window_handle windows = driver.window_handles for current_window in windows: if current_window != window_1: driver.switch_to.window(current_window) (3) # Click on a course in the course library to enter the course details screen [Click on an element in the second window page to determine whether the window is switched successfully]. driver.find_element_by_xpath('//*[@]/ul/li[2]').click() (3) # Close the browser () print('Test passed')
Difference between the two methods:
1, the first method is relatively simple, can improve the overall performance of the code
2. The second method is the one most commonly used by everyone and is easier to understand
Above this python3 selenium switch window several methods of summary is all I share with you, I hope to give you a reference, and I hope you support me more.