验证码: 看不清楚,换一张 查询 注册会员,免验证
  • {{ basic.site_slogan }}
  • 打开微信扫一扫,
    您还可以在这里找到我们哟

    关注我们

怎么使用Selenium自动化测试实现窗口切换

阅读:748 来源:乙速云 作者:代码code

怎么使用Selenium自动化测试实现窗口切换

在Web自动化测试过程中,有时单击某个链接会弹出新的窗口,这时就需要切换到新打开的窗口中进行操作。WebDriver 提供的switch_to.window()方法可以实现在不同的窗口之间进行切换。

主要用到的相关方法:

  • current_window_handle:获得当前窗口句柄。

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

  • switch_to.window():切换到相应的窗口

下面以百度首页和账号注册页为例,演示在两个窗口之间的切换

import time
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.implicitly_wait(10)

driver.get("https://www.baidu.com")
search_windows = driver.current_window_handle

driver.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(driver.title)
        driver.find_element(By.NAME,'userName').send_keys('userName')
        driver.find_element(By.NAME,'phone').send_keys('138xxxxxxx')
        time.sleep(2)

        driver.close()

driver.switch_to.window(search_windows)
print(driver.title)
driver.quit()

解析:程序开始后,首先打开百度首页,然后通过current_window_handle获取了当前窗口句柄,接着打开登录弹窗,点击注册按钮从而打开新窗口;再通过window_handles 获得当前所有窗口句柄,接着遍历所有窗口句柄,如果不等于百度首页的窗口句柄,那就是注册页的窗口句柄,因为只打开了两个窗口,然后再通过switch_to.window()切换到注册页窗口。

分享到:
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: hlamps#outlook.com (#换成@)。
相关文章
{{ v.title }}
{{ v.description||(cleanHtml(v.content)).substr(0,100)+'···' }}
你可能感兴趣
推荐阅读 更多>