处理多个窗口

Python

最常用的场景:

  1. 在新窗口中打开页面
  2. 切换到它
  3. 做一点事
  4. 关闭它
  5. 切换回父窗口
# Open "Google" page in parent window
driver.get("https://google.com")

driver.title # 'Google'

# Get parent window
parent_window = driver.current_window_handle 

# Open "Bing" page in child window
driver.execute_script("window.open('https://bing.com')") 

# Get list of all windows currently opened (parent + child)
all_windows = driver.window_handles 

# Get child window
child_window = [window for window in all_windows if window != parent_window][0] 

# Switch to child window
driver.switch_to.window(child_window) 

driver.title # 'Bing'

# Close child window
driver.close() 

# Switch back to parent window
driver.switch_to.window(parent_window) 

driver.title # 'Google'