selenium - switch_to.window() - 多窗口切换
在页面操作过程中有时候点击某个链接会弹出新的窗口,这时就需要主机切换到新打开的窗口上进行操作。WebDriver提供了switch_to.window()方法,可以实现在不同的窗口之间切换。
以百度首页为例:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
from selenium import webdriverimport timedriver = webdriver.Chrome()driver.implicitly_wait(10)driver.get("http://www.baidu.com")#获得百度搜索窗口的句柄search_windows = driver.current_window_handledriver.find_element_by_link_text('登录').click()driver.find_element_by_link_text('立即注册').click()#获得当前所有打开窗口的句柄all_handles = driver.window_handles#进入注册窗口for handle in all_handles: if handle != search_windows: driver.switch_to_window(handle) print('now register window!') driver.find_element_by_name('userName').send_keys('ZeiTe9834') driver.find_element_by_xpath("//*[@id='TANGRAM__PSP_3__password']").send_keys('ZeiTe9834') time.sleep(5) driver.quit() |
- current_window_handle:获得当前窗口句柄。
- window_handles:返回所有窗口的句柄到当前会话。
- switch_to.window():用于切换到相应的窗口,与上一节的switch_to.frame()类似,前者用于不同窗口的切换,后者用于不同表单之间的切换
浙公网安备 33010602011771号