思路:
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