Selenium+java - 通过Robot对象上传文件

前端之家收集整理的这篇文章主要介绍了Selenium+java - 通过Robot对象上传文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

思路:

1、将文件路径复制到剪切板

2、用robot对象模拟键盘操作即可

复制文件代码

 public void setClipboardData(String data) {
        StringSelection stringSelection = new StringSelection(data);
        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection,null);
    }

实现上传代码

package com.brower.demo;

import org.openqa.selenium.By;
 org.openqa.selenium.WebDriver;
 org.openqa.selenium.chrome.ChromeDriver;
 org.testng.annotations.AfterClass;
 org.testng.annotations.BeforeClass;
 org.testng.annotations.Test;

import java.awt.*;
 java.awt.datatransfer.StringSelection;
 java.awt.event.KeyEvent;
 java.io.IOException;

/**
 * @author rongrong
 */
class TestUploadByRobot {
    WebDriver driver;

    @BeforeClass
     beforeClass() {
        System.setProperty("webdriver.chrome.driver","driver/chromedriver.exe");
        driver =  ChromeDriver();
    }

    @Test
    void testUploadByRobot() throws AWTException {
        driver.get("file:///C:/Users/Administrator/Desktop/upload.html");
        driver.manage().window().maximize();
        //选择文件
        driver.findElement(By.id("upload")).click();
        setClipboardData("F:\\robotium-solo-5.6.1.jar");
        Robot robot =  Robot();
        robot.keyPress(KeyEvent.VK_TAB);
        robot.delay(100);
        robot.keyRelease(KeyEvent.VK_TAB);
        robot.keyPress(KeyEvent.VK_TAB);
        robot.delay(100);
        robot.keyRelease(KeyEvent.VK_TAB);
        robot.keyPress(KeyEvent.VK_ENTER);
        robot.delay(100);
        robot.keyRelease(KeyEvent.VK_ENTER);
        robot.keyPress(KeyEvent.VK_CONTROL);
        robot.keyPress(KeyEvent.VK_V);
        robot.keyRelease(KeyEvent.VK_V);
        robot.keyRelease(KeyEvent.VK_CONTROL);
        robot.delay(100);
        robot.keyRelease(KeyEvent.VK_ENTER);

    }

    );
    }


    @AfterClass
     afterClass() {
        driver.quit();
    }

}

效果

 

原文链接:/selenium/992262.html

猜你在找的Selenium相关文章