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()
相关推荐
Lossya4 分钟前
【自动化测试】常见的自动化遍历工具以及如何选择合适的自动化遍历工具
自动化测试·功能测试·测试工具·自动化·测试
Lossya4 小时前
【自动化测试】UI自动化的分类、如何选择合适的自动化测试工具以及其中appium的设计理念、引擎和引擎如何工作
自动化测试·测试工具·ui·appium·自动化
waterHBO14 小时前
python 爬虫 selenium 笔记
爬虫·python·selenium
chenjingming6661 天前
windows使用tcpdump.exe工具进行抓包教程
网络·测试工具·tcpdump
小码哥说测试1 天前
软件测试技术之 GPU 单元测试是什么!
自动化测试·功能测试·测试工具·jmeter·单元测试·集成测试·postman
全能全知者2 天前
不废话简单易懂的Selenium 页面操作与切换
python·selenium·测试工具·网络爬虫
测试19982 天前
使用Selenium进行网页自动化
自动化测试·软件测试·python·selenium·测试工具·自动化·测试用例
做一道光2 天前
1、QAC静态测试常用操作
软件测试·测试工具·静态测试
假女吖☌2 天前
postman接口关联
测试工具·postman
测试杂货铺2 天前
selenium元素定位:元素点击交互异常解决方法
自动化测试·软件测试·python·selenium·测试工具·职场和发展·单元测试