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()
相关推荐
williamdsy2 小时前
专业的办公家具解决方案
测试工具
williamdsy3 小时前
专业的办公家具哪家技术强
测试工具
williamdsy5 小时前
好用的办公家具源头厂家
测试工具
UTP协同自动化测试9 小时前
智能家居中控屏测试:触摸屏操作 + I2C 读取传感器 + UART 与子设备通信 + GPIO 控制
功能测试·单片机·嵌入式硬件·测试工具·智能家居
大汉堡玩测试1 天前
抓包工具Whistle的安装与使用
测试工具
oi..1 天前
Linux入门(2)
linux·笔记·测试工具·安全·网络安全
路飞雪吖~1 天前
【测试】接口测试---1个框架,5个模块
开发语言·python·测试工具
独断万古他化1 天前
基于 Selenium + POM 模式的聊天室系统 UI 自动化测试框架搭建与实践
selenium·测试工具·ui·自动化·测试·pom
Wild_Pointer.2 天前
高效工具实战指南:Beyond Compare文件比较工具
测试工具
Three~stone2 天前
Wireshark 4.6.4 安装教程
网络·测试工具·wireshark