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()
相关推荐
巴里巴气6 小时前
对selenium进行浏览器和驱动进行配置Windows | Linux
selenium·测试工具
q5673152320 小时前
Java Selenium反爬虫技术方案
java·爬虫·selenium
有趣的我1 天前
wireshark介绍和使用
网络·测试工具·wireshark
草履虫建模1 天前
Postman - API 调试与开发工具 - 标准使用流程
java·测试工具·spring·json·测试用例·postman·集成学习
龙潜月七1 天前
Selenium 自动化测试中跳过机器人验证的完整指南:能用
python·selenium·机器人
AIZHINAN1 天前
如何评价 selenium 自动化测试框架搭建?
selenium·测试工具
WIN赢11 天前
PostMan使用
测试工具·lua·postman
百里图书12 天前
颠覆传统接口测试!用 Streamlit + SQLite + GPT 打造可视化自动化平台
自动化测试·测试开发·接口自动化测试·测试工具·接口测试·测试平台·python编程
笑口常开的小丸子12 天前
Selenium等待机制详解:从原理到实战应用
selenium
网络安全小吗喽12 天前
靶场(二十六)---小白心得&&靶场体会---Readys
服务器·网络·测试工具·网络安全·靶机