python selenium open a new window, switch between multiple windows

# coding=utf-8

from selenium import webdriver

browser=webdriver.Firefox()
browser.maximize_window() # maximize the window

browser.get('https://www.baidu.com') # Visit Baidu in the current browser

# Open a new window, open a new window by executing js
js='window.open("https://www.sogou.com");'
browser.execute_script(js)

print (browser.current_window_handle) # Output the current window handle (Baidu)
handles = (browser.window_handles) # Get the current window handle collection (list type)
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 (browser.current_window_handle) # Output the current window handle (Sogou)
        break

browser.close() # Close the current window (Sogou)
browser.switch_to_window(handles[0]) # Switch back to Baidu window
import time
time.sleep(10)
browser.quit()

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324807469&siteId=291194637