两个方法
driver.current_window_handle 获取当前窗口句柄
driver.window_handles 获取所有窗口句柄
1 from selenium import webdriver 2 from selenium.webdriver.common.by import By 3 from time import sleep 4 from selenium.common.exceptions import NoSuchElementException 5 6 driver = webdriver.Chrome() 7 8 driver.implicitly_wait(10) 9 url = "http://192.168.117.9/bbs/upload/forum.php" 10 driver.get(url) 11 12 try: 13 """清除cookies""" 14 driver.delete_all_cookies() 15 16 """登录""" 17 driver.find_element(By.ID, 'ls_username').send_keys('admin') 18 addr = driver.find_element(By.NAME, 'password') 19 addr.clear() 20 addr.send_keys('admin') 21 '''提交登录''' 22 driver.find_element(By.CSS_SELECTOR, "[type='submit']").click() 23 sleep(2) 24 25 """获取首页窗口句柄""" 26 home_windows = driver.current_window_handle 27 print(home_windows) 28 29 """进入管理中心""" 30 driver.find_element_by_css_selector("[href='admin.php']").click() 31 sleep(2) 32 33 """获取所有窗口句柄""" 34 all_windows = driver.window_handles 35 print(all_windows) 36 37 """切换窗口""" 38 for i in all_windows: 39 if i != home_windows: 40 """切换到指定的window_name页签""" 41 driver.switch_to.window(i) 42 now_url = driver.current_url 43 print(now_url) 44 sleep(5) 45 46 """返回首页窗口""" 47 for v in all_windows: 48 if v == home_windows: 49 driver.switch_to.window(v) 50 print(driver.current_url) 51 52 except NoSuchElementException as e: 53 print(e) 54 55 finally: 56 """关闭当前窗口""" 57 # driver.close() 58 """关闭浏览器""" 59 sleep(5) 60 driver.quit()