# Coding=utf-8
From selenium import Webdriver
Import time
Browser=webdriver. Firefox ()
#browser. Maximize_window () # window maximization
Browser.get (' https://www.baidu.com ') # accessing Baidu in the current browser
Print ("title:" +browser.title,end= "\ n Current Window handle")
Print (browser.current_window_handle) # Output Current Window handle (Baidu)
# Open a new window, by executing JS to open a new window
Js= ' window.open ("https://www.sogou.com");
Browser.execute_script (JS)
Handles = Browser.window_handles # Gets the current Window handle collection (list type)
Print ("All window handles:")
Print (handles) # Output handle Collection
For handle in handles:# switch window (switch to Sogou)
If Handle!=browser.current_window_handle:
Print (' Switch to ', handle)
Browser.switch_to_window (handle)
Print ("title:" +browser.title,end= "\ n Current Window handle:")
Print (browser.current_window_handle) # Output Current Window handle (Sogou)
Break
Browser.close () #关闭当前窗口 (Sogou)
Browser.switch_to_window (Handles[0]) #切换回百度窗口
Print ("title:" +browser.title)
Import time
Time.sleep (5)
Browser.quit ()
Completely solve the problem of browser multi-window opening and switching under Python