selenium-多窗口和frame处理

1.切换窗口

适用场景:点击按钮后,重新打开一个窗口,想要在新的窗口定位操作,就需要切换窗口

原理:获取窗口的唯一标识就是句柄,获取到句柄,就可以切换到对应的窗口了

处理方法:

  • 获取到当前的窗口柄(driver.current_window_handle)
  • 获取到所有的窗柄 (driver.window_handles)
  • 判断是否是想要操作的窗口,如果是,就可以对窗口进行操作,如果不是跳转到另外一个窗口,对另一个窗口进行操作(driver.switch_to.window)

示例(百度搜索页和百度新闻页):

python 复制代码
class TestDemo():
    def setup(self):
        self.driver = webdriver.Chrome()
        self.driver.maximize_window()
        self.driver.implicitly_wait(3)  
  
    def test_baidu(self):
        self.driver.get("https://www.baidu.com/")
        search_window = self.driver.current_window_handle
        self.driver.find_element_by_xpath("//*[@id='s-top-left']/a[1]").click()
        handles = self.driver.window_handles
        print(handles)
        for handle in handles:
            if handle != search_window:
               self.driver.switch_to.window(handle)
               print(self.driver.title)
               self.driver.find_element_by_id('ww').send_keys('autotest')
               self.driver.find_element_by_id('s_btn_wr').click()

2.处理frame

什么是frame?

frame是html中的框架,在html中,frame可以在同一个窗口中显示不止一个页面。

Frame分类

frame标签包含frameset、frame、iframe三种

frameset和普通的标签一样,不会影响正常的定位,可以使用index、id、name、webelement任意种方式定位frameset

而frame与iframe对selenium定位而言是一样的。selenium有一组方法对frame进行操作

注意:一个页面中可能存在多个frame;一个frame中可能嵌套frame

处理方法:

  • 跳转到frame:switch_to.frame(frame_reference) --frame_reference用于定位frame,可以是id,name,index,也可以是selenium获得WebElement对象。
  • 嵌套frame先进入父类frame再进入子frame,才可以对子frame中的元素处理
python 复制代码
driver.switch_to.frame('id') #id
driver.switch_to.frame('name') #name
driver.switch_to.frame('0') #index
driver.switch_to.frame(driver.find_element_by_xpath('path'))#也可以用css等定位方式
  • 跳转出frame :switch_to.default_content()
  • 切换到父级frame :switch_to.parent_frame()

示例(qq邮箱登录页面):

python 复制代码
def test_frame(self):
    self.driver.get("https://mail.qq.com/")

    self.driver.switch_to.frame(self.driver.find_element_by_xpath('//*[@id="QQMailSdkTool_login_loginBox_qq"]/iframe'))#切换到父类frame
    self.driver.switch_to.frame('ptlogin_iframe')#切换到frame
    time.sleep(3)
    self.driver.find_element_by_xpath('//*[@id="switcher_plogin"]').click()
    self.driver.switch_to.default_content()#跳出frame
    self.driver.find_element_by_class_name('header_logo').click()
相关推荐
川石课堂软件测试5 小时前
使用mock进行接口测试教程
数据库·python·功能测试·测试工具·华为·单元测试·appium
程序员杰哥10 小时前
接口自动化测试:多环境配置实战
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·接口测试
XINERTEL1 天前
视频卡顿花屏?专业视频质量评估测试让画质从“凭感觉”到“数据说话”
网络·测试工具·音视频·丢包
Luminbox紫创测控1 天前
氙弧老化测试全参数解析:滤镜类型、辐照度与黑标温度设定
人工智能·测试工具·安全性测试·测试标准
麦科信仪器1 天前
一文读懂麦科信AHO1系列高分辨率汽车示波器
测试工具
程序员小远2 天前
系统性能指标全解析
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·性能测试
@我们的天空2 天前
Claude Code + GLM-5 深度赋能测试:开发 8 大 Skill 构建 AI 测试助手集群
人工智能·python·测试工具·自动化·ai编程
PhotonixBay2 天前
激光共聚焦与白光干涉仪在PCB表面轮廓测量中的原理与数据对比
人工智能·测试工具·制造