前言
本文为在霍格沃兹测试开发学社的学习经历分享,希望有志同道合的小伙伴可以一起交流技术,一起进步~
frame
1. 多窗口处理
- 点击某些链接时,会跳转到另一个窗口,这时候想要在新也买你上操作,就要切换窗口。
- 获取窗口的唯一标识用句柄表示,所以只需要切换句柄,就可以在多个页面灵活操作了
处理步骤:
- 获取到当前的窗口句柄:(driver.current_window_handle)
- 获取到所有的窗口句柄:(driver.window_handles)
- 判断是否是想要操作的窗口,如果是,就可以直接对窗口进行操作,如果不是,可以用(driver.switch_to_window)方法切换到另一个窗口
2. frame是html的一个框架,框架就是可以在同一个浏览器中显示不止一个界面。
- 在web自动化中,如果一个元素定位不到,很有可能是在iframe中
- frame标签包括frameset,frame,iframe三种
- frameset和普通标签一样,不影响正常定位
- 而frame和iframe对selenium定位而言是一样的,selenium对frame的操作如下:
3. 多frame切换
frame存在两种,一种是嵌套的,一种是未嵌套的
-
切换frame
- driver.switch_to.frame() 根据元素id或者index切换frame
- driver.switch_to.default_content() 切换到默认frame
- driver.switch_to.parent_frame() 切换到父级frame
-
未嵌套frame
- driver.switch_to.frame(“frame的id”)
- driver.switch_to.frame(“frame - index”) frame无ID的时候依据索引来处理,索引从0开始。例如:driver.switch_to.frame(0)
-
嵌套frame
- 对于嵌套的先进入iframe的父节点,再进到子节点,然后可以对子节点里的对象进行操作
4. 案例:
class TestFrame(Base):
def test_frame(self):
self.driver.get("https://www.runoob.com/try/try.php?filename=jqueryui-api-droppable")
self.driver.switch_to.frame("iframeResult")
# 新版本的selenium已经删除了这种用法, 不推荐使用
# self.driver.switch_to_frame("iframeResult")
print(self.driver.find_element(By.ID,"draggable").text)
self.driver.switch_to.default_content()
print(self.driver.find_element(By.ID,"submitBTN").text)
弹窗处理
在页面操作中有时会遇到JavaScript所生成的alert,confirm以及prompt弹窗,可以使用switch_to.alert() 方法定位到,然后使用text/accept/dismiss/send_keys等方法进行操作。
alert常用方法
- switch_to.alert():获取当前页面上的警告框
- text:返回alert/confirm/prompt中的文字信息
- accept():接受现有警告框
- dismiss():解散现有警告框
- send_keys(keysToSend):发送文本至警告框。keysToSend文本路径。
示例:
def test_alert(self):
self.driver.get("https://www.runoob.com/try/try.php?filename=jqueryui-api-droppable")
self.driver.switch_to_frame("iframeResult")
action = ActionChains(self.driver)
drag = self.driver.find_element(By.ID, "draggable")
drop = self.driver.find_element(By.ID,"droppable")
# 点击拖拽到drop
action.drag_and_drop(drag,drop).perform()
sleep(2)
print("点击 alert 确认")
# 获取当前页面的警告框,接受警告框
self.driver.switch_to_alert().accept()
# 切换回默认的frame下,即切换回主文档
self.driver.switch_to_default_content()
self.driver.find_element(By.ID,"submitBTN").click()
sleep(3)
switch_to.frame()方法就是从原本的主层定位到嵌套层里,就能定位到嵌套层里的元素;但是使用完上面的方法后,就无法定位到原来主层元素,那就得使用switch_to.default_content()方法,可以回退到主层了。
文件上传
class TestFile(Base):
def test_file_upload(self):
self.driver.get("https://image.baidu.com")
self.driver.find_element(By.ID,"sttb").click()
sleep(2)
self.driver.find_element(By.ID,"stfile").send_keys(r"C:\Users\Administrator\Desktop\picture\1.jpg")
推荐阅读文章链接:接口测试经典面试题:Session、cookie、token有什么区别?_霍格沃兹测试开发学社的博客-CSDN博客