(二十三)WebDriver API之多窗口切换

随笔记录方便自己和同路人查阅。

#------------------------------------------------我是可耻的分割线-------------------------------------------

  学习selenium自动化之前,最好先学习HTML、CSS、JavaScript等知识,有助于理解定位及操作元素的原理。关于python和selenium安装请自行搜索别的资料,

这里就不多做介绍了,所有例子均使用python3.6+selenium执行的。

  通过两个实例分别使用switch_to_window和switch_to.window方法

#------------------------------------------------我是可耻的分割线-------------------------------------------

多窗口切换

在页面操作过程中有时候点击某个链接会弹出新的窗口,这时就需要主机切换到新打开的窗口上进行操作。WebDriver提供了switch_to.windos()方法,可以实现在不同窗口之间切换。

一、以百度首页和百度注册页为例,在两个窗口之间的切换。

from selenium import webdriver
import time

driver = webdriver.Chrome()
driver.implicitly_wait(10)
driver.get('http://www.baidu.com')

#获得白底搜索窗口句柄
sreach_windows = driver.current_window_handle

time.sleep(2)
driver.find_element_by_link_text('登录').click()
time.sleep(2)
driver.find_element_by_link_text('立即注册').click()
time.sleep(2)
#获得当前所有打开的窗口句柄
all_handles = driver.window_handles

#进入注册窗口
for hanle in all_handles:
    if hanle != sreach_windows:#不等于百度首页句柄就执行下面代码
        driver.switch_to.window(hanle)#进入不等于百度首页句柄页
        print('now register window!')
        driver.find_element_by_name('userName').send_keys('ww')
        driver.find_element_by_name('phone').send_keys('password')
        time.sleep(2)
#回到搜索窗口
driver.switch_to_window(sreach_windows)
print('onw sreach window!')

#关闭登录对话框
driver.find_element_by_id('TANGRAM__PSP_4__closeBtn').click()

driver.find_element_by_id('kw').send_keys('selenium')
driver.find_element_by_id('su').click()

  效果展示:

  1、首先打开百度首页,通过current_window_handle获得当前窗口的句柄并赋值给sreach_handle2、然后点击登录按钮,打开登入弹窗;3、点击注册按钮、通过window_handles获得当前打开的所有窗口句柄并保存在变量all_handles4、返回百度首页;5、在百度首页输入框输入selenium6、点击搜索按钮。

  switch_to.window():用于切换到相应的窗口。

  二、QQ邮箱登入实例,我们先打开QQ登录页面,然后在打开注册页面,最后再在QQ登入页面输入用户名,来完成多窗口的切换。

from selenium import webdriver
import time as t

driver = webdriver.Chrome()
driver.maximize_window()
driver.implicitly_wait(30)
driver.get('https://mail.qq.com/cgi-bin/loginpage')
driver.switch_to_frame('login_frame')#进入frame框架
name = driver.find_element_by_class_name('input_tips')
print('QQ邮箱输入框中提示为:{0}'.format(name.text))
print('检查是否可编辑:{0}'.format(name.is_enabled()))
driver.find_element_by_id('forgetpwd').click()
now_handle = driver.current_window_handle#保存现在句柄
handles = driver.window_handles#保存全部句柄
print(handles)
print(now_handle)
for handle in handles:
    if handle != now_handle:
        driver.switch_to_window(handle)
        driver.find_element_by_xpath('//*[@id="input_find_qq"]').send_keys('11111@qq.com')
        print(handle)
        t.sleep(2)
        driver.close()
driver.switch_to_window(now_handle)
driver.switch_to_frame('login_frame')
driver.find_element_by_class_name('inputstyle').send_keys('username')
原文地址:https://www.cnblogs.com/lirongyang/p/11457983.html