slenium 随手记 (一) 切换窗口

q=a.current_window_handle 获取当前的窗口句柄    w= a.window_handles 获取所以窗口的句柄    a.switch_to_window(a.window_handles[1]) 切换窗口    a.switch_to_window(w[1]) 切换窗口  

#coding=utf-8

from selenium import webdriver

driver = webdriver.Firefox()

driver.implicitly_wait(10)

driver.get("http://www.baidu.com")

#获得百度搜索窗口句柄

sreach_windows= driver.current_window_handle

driver.find_element_by_link_text(u'登录').click()

driver.find_element_by_link_text(u"立即注册").click()

#获得当前所有打开的窗口的句柄

all_handles = driver.window_handles

#进入注册窗口

for handle in all_handles:

if handle != sreach_windows:

driver.switch_to_window(handle)

print 'now register window!'

driver.find_element_by_name("account").send_keys('username')

driver.find_element_by_name('password').send_keys('password')

#……

#进入搜索窗口

for handle in all_handles:

if handle == sreach_windows:

driver.switch_to_window(handle)

print 'now sreach window!'

driver.find_element_by_id('TANGRAM__PSP_2__closeBtn').click()

driver.find_element_by_id("kw").send_keys("selenium")

driver.find_element_by_id("su").click()

time.sleep(5)

driver.quit()

整个脚本的处理过程:首先打开百度首页,通过 current_window_handle 获得当前窗口的句柄,并给变

量 sreach_handle。接着打开登录弹窗,在登录窗口上点击“立即注册”从而打开新的注册窗口。通过

window_handles 获得当前打开的所窗口的句柄,赋值给变量 all_handles。

第一个循环遍历 all_handles,如果 handle 不等于 sreach_handle,那么一定是注册窗口,因为脚本执行

只打开的两个窗口。所以,通过 switch_to_window()切换到注册页进行注册操作。第二个循环类似,不过

这一次判断如果 handle 等于 sreach_handle,那么切换到百度搜索页,关闭之前打开的登录弹窗,然后时行

搜索操作。

在本例中所有用到的新方法:

current_window_handle 获得当前窗口句柄

window_handles 返回的所有窗口的句柄到当前会话

switch_to_window()

用于切换到相应的窗口,与上一节的 switch_to_frame() 是类似,前者用于不同窗口的切换,后者用于

不同表单之间的切换。

posted @ 2016-04-01 14:26  余伟东  阅读(546)  评论(0)    收藏  举报