This script opens a page with a button that opens a new window. It switches to the new window, prints its title, closes it, then switches back and prints the main window's title.
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
# Setup driver (make sure chromedriver is in PATH)
driver = webdriver.Chrome()
# Open first page
driver.get('https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_win_open')
# Save main window handle
main_window = driver.current_window_handle
# Click button that opens new window
# Switch to iframe first because button is inside iframe
iframe = driver.find_element(By.ID, 'iframeResult')
driver.switch_to.frame(iframe)
button = driver.find_element(By.TAG_NAME, 'button')
button.click()
# Wait for new window to open
time.sleep(2)
# Get all window handles
all_windows = driver.window_handles
# Switch to new window (last one)
driver.switch_to.window(all_windows[-1])
# Print title of new window
print('New window title:', driver.title)
# Close new window
driver.close()
# Switch back to main window
driver.switch_to.window(main_window)
# Print title of main window
print('Main window title:', driver.title)
driver.quit()