页面操作中,点击某个链接会打开新的窗口,定位新窗口中的元素,需要跳转到新窗口操作,可以使用以下方法:
- current_window_handle
- window_handles
- switch_to.window(handle)
例子:
1. 打开百度首页,点击登录按钮,点击立即注册按钮,打开新的窗口
2. 跳转到注册窗口,在注册窗口进行操作
3. 跳回到百度首页,点击登录弹出框的关闭按钮,在百度首页进行操作
1 from selenium import webdriver 2 import time 3 4 driver = webdriver.Chrome() 5 driver.maximize_window() 6 driver.get('http://www.baidu.com') 7 8 search_window = driver.current_window_handle # 获取当前窗口句柄 9 time.sleep(3) 10 driver.find_element_by_link_text('登录').click() 11 time.sleep(3) 12 driver.find_element_by_link_text('立即注册').click() 13 14 all_window_handles = driver.window_handles # 获取当前所有打开窗口的句柄 15 16 for handle in all_window_handles: 17 if handle != search_window: 18 driver.switch_to.window(handle) # 跳转到注册窗口 19 driver.find_element_by_id('TANGRAM__PSP_4__userName').send_keys('jda') 20 driver.find_element_by_id('TANGRAM__PSP_4__phone').send_keys('13100000000') 21 driver.find_element_by_id('TANGRAM__PSP_4__password').send_keys('fda') 22 time.sleep(3) 23 24 for handle in all_window_handles: 25 if handle == search_window: 26 driver.switch_to.window(handle) # 跳转到百度首页窗口 27 driver.find_element_by_id('TANGRAM__PSP_4__closeBtn').click() 28 driver.find_element_by_id('kw').send_keys('zhangyang') 29 driver.find_element_by_id('su').click() 30 time.sleep(3) 31 32 driver.quit()