自动化测试 - 文件上传 和 弹窗处理

文章目录

    1. 文件上传处理
    • 1.1 没有 input 标签 -比较复杂一点
    • 1.2 上传按钮button中有 input 标签 -比较简单
    1. Alert 弹窗处理
    • 2.1 弹窗可以对应元素-html中可以找到弹窗元素
    • 2.2 弹窗无法在html中定位元素-使用Alert
  • 总结

✨✨✨学习的道路很枯燥,希望我们能并肩走下来!

编程真是一件很奇妙的东西。你只是浅尝辄止,那么只会觉得枯燥乏味,像对待任务似的应付它。但你如果深入探索,就会发现其中的奇妙,了解许多所不知道的原理。知识的力量让你沉醉,甘愿深陷其中并发现宝藏。



本文开始

1. 文件上传处理

1.1 没有 input 标签 -比较复杂一点

没有 input 标签

1.选择上传按钮传入,通过JS构造Input标签上传脚本,生成后删除对应Input

java 复制代码
/**
     * 上传文件按钮,没有Input标签, 使用JS构建一个input, 上传后再删除
     */
    public void noInput() {
    	WebDriver webDriver1 = WebDriverManager.chromedriver().create();
        // 1. 设置隐式等待(可选)
        webDriver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
        // 2. 打开页面
        String url = "你的页面URL"; // 请填写实际URL
        webDriver.get(url);
        // 3. 点击上传按钮
        WebElement noInputEle = webDriver.findElement(By.xpath("//*[text()='点击上传']"));
        noInputEle.click();
        // 4. 给页面一点时间响应(如果需要)
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 5. 创建隐藏的input元素并上传文件
        String filePath = "D:\\first_demo\\pom.xml";

        // 直接使用一个简化的脚本,创建并设置文件
        String script = """
            // 创建file input元素
            var fileInput = document.createElement('input');
            fileInput.type = 'file';
            fileInput.id = 'selenium-auto-upload-file';
            fileInput.style.display = 'none';
            document.body.appendChild(fileInput);
            
            // 返回这个元素供Selenium操作
            return fileInput;
         """;

        // 执行脚本获取input元素
        WebElement jsInput = (WebElement) ((JavascriptExecutor) webDriver).executeScript(script);

        // 设置文件路径
        jsInput.sendKeys(filePath);

        // 6. 触发change事件(模拟用户选择文件后的行为)
        String triggerScript = """
            // 获取刚创建的input
            var fileInput = document.getElementById('selenium-auto-upload-file');
            if (fileInput) {
                // 创建并触发change事件
                var event = new Event('change', { bubbles: true });
                fileInput.dispatchEvent(event);
                
                // 也可以尝试触发input事件
                var inputEvent = new Event('input', { bubbles: true });
                fileInput.dispatchEvent(inputEvent);
            }
        """;

        ((JavascriptExecutor) webDriver).executeScript(triggerScript);

        // 7. 验证文件是否已设置(可选)
        String checkScript = """
            var fileInput = document.getElementById('selenium-auto-upload-file');
            if (fileInput && fileInput.files && fileInput.files.length > 0) {
                return fileInput.files[0].name;
            }
            return null;
        """;

        String fileName = (String) ((JavascriptExecutor) webDriver).executeScript(checkScript);
        if (fileName != null) {
            System.out.println("文件已设置: " + fileName);
        } else {
            System.out.println("文件设置失败");
        }

        // 8. 等待上传完成(根据实际需要调整时间)
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 9. 清理(可选,如果页面需要可以保留)
         ((JavascriptExecutor) webDriver).executeScript(
             "document.getElementById('selenium-auto-upload-file')?.remove();"
         );

        System.out.println("上传操作完成");

    }

1.2 上传按钮button中有 input 标签 -比较简单

有input标签:

1.找到文件对应的 input 标签。

2.定位到对应的文件地址,使用send_keys/sendKeys,输入文件路径,就会进行文件上传

操作方法:

文件上传

(Java):sendKeys("文件路径")

(Python):send_keys("文件路径")

java 复制代码
/**
     * 上传文件中有 input 标签,可以直接采用元素定位,往input中输入文件路径
     */
    public void fileTest() {
        List<Executable> executableList = new ArrayList<>();
        //1.获取驱动
        WebDriver webDriver1 = WebDriverManager.chromedriver().create();
        //2.设置隐式等待
        webDriver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
        //3.打开页面
        String url = "你的url";
        webDriver.get(url);
        //4.执行上传文件逻辑
        WebElement load_element = webDriver.findElement(By.xpath("//*[@id='fileInput']"));
        load_element.sendKeys("D:\\first_demo\\pom.xml");
        //验证上传成功
        WebElement h1Ele = webDriver.findElement(By.xpath("//*[@id='fileInput']/../h1"));
        String text = h1Ele.getText();
        System.out.println("h1: " + text);
        executableList.add(() -> assertThat(text, equalTo("pom.xml")));
        assertAll();
    }

2. Alert 弹窗处理

2.1 弹窗可以对应元素-html中可以找到弹窗元素

出现弹窗,查找html中是否有对应元素;

如:有可能是一个div标签;

如果弹窗可以找到对应元素,直接定位元素处理即可。

java 复制代码
/**
     * 能在html中找到元素的弹窗处理-元素定位
     */
    @Test
    public void tanChuang() {
        //1.获取驱动
        WebDriver webDriver1 = WebDriverManager.chromedriver().create();
        //2.设置隐式等待
        webDriver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
        //3.进入页面
        String url = "https://study_up_up/file_down";
        webDriver.get(url);
        //4.点击两次显示弹窗
        WebElement element = webDriver.findElement(By.xpath("//*[text()='点击两次响应']"));
        element.click();
        element.click();
        WebElement tanChangEle = webDriver.findElement(By.xpath("//*[contains(text(), '确定')]"));
        tanChangEle.click();
    }

2.2 弹窗无法在html中定位元素-使用Alert

弹窗不在html中,所以没办法使用元素定位,所以需要使用Alert方法

如果弹窗无法定位,则需要使用 Alert 对应方法处理。

java 复制代码
 /**
     * alert弹窗处理:需要切换到alert弹窗中,调用alert中的方法处理
     */
    @Test
    public void alertTest() {
        //1.获取驱动
        WebDriver webDriver1 = WebDriverManager.chromedriver().create();
        //2.设置隐式等待
        webDriver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
        //3.进入页面
        String url = "https://study_up_up/file_down";
        webDriver.get(url);
        //4.弹窗操作逻辑
        WebElement alertEle = webDriver.findElement(By.xpath("//*[@id='warning_btn']"));
        alertEle.click();
        //4.1需要切换到Alert弹窗, 获取弹窗文本
        Alert alert = webDriver.switchTo().alert();
        String alertText = alert.getText();
        System.out.println("alertText: " + alertText);
        //4.2 点击 alert 弹窗确定按钮
        alert.accept();
    }

弹窗常用操作:

  • 获取弹框文本
    java: alert.getText()
    python: text
  • 点击弹窗中的确认按钮
    java: alert.accept()
    python: accept()
  • 点击弹窗中的取消按钮
    java: alert.dismiss()
    python: dismiss()
  • 在弹窗中输入文本内容
    java: alert.sendKeys(text)
    python: send_keys(text)

总结

✨✨✨各位读友,本篇分享到内容是否更好的帮助你理解,如果对你有帮助给个👍赞鼓励一下吧!!
🎉🎉🎉世上没有绝望的处境,只有对处境绝望的人。
🎉🎉🎉一遇挫折就灰心丧气的人,永远是个失败者。而一向努力奋斗,坚韧不拔的人会走向成功。
感谢每一位一起走到这的伙伴,我们可以一起交流进步!!!一起加油吧!!!

相关推荐
LinHenrY12272 小时前
初识C语言(编译和链接)
c语言·开发语言·蓝桥杯
_OP_CHEN2 小时前
【Python基础】(二)从 0 到 1 入门 Python 语法基础:从表达式到运算符的全面指南
开发语言·python
l1t2 小时前
利用小米mimo为精确覆盖矩形问题C程序添加打乱函数求出更大的解
c语言·开发语言·javascript·人工智能·算法
composurext2 小时前
录音切片上传
前端·javascript·css
我命由我123452 小时前
Python Flask 开发:在 Flask 中返回字符串时,浏览器将其作为 HTML 解析
服务器·开发语言·后端·python·flask·html·学习方法
程序员小寒2 小时前
前端高频面试题:深拷贝和浅拷贝的区别?
前端·javascript·面试
csbysj20202 小时前
Scala 类和对象
开发语言
拾忆,想起2 小时前
设计模式:软件开发的可复用武功秘籍
开发语言·python·算法·微服务·设计模式·性能优化·服务发现
狮子座的男孩2 小时前
html+css基础:07、css2的复合选择器_伪类选择器(概念、动态伪类、结构伪类(核心)、否定伪类、UI伪类、目标伪类、语言伪类)及伪元素选择器
前端·css·经验分享·html·伪类选择器·伪元素选择器·结构伪类