处理文件上传有以下四种方法:
1.可以通过sendkey--input标签即可
WebElement element4= driver2.findElement(By.xpath("/html/body/div[4]/div[2]/div[2]/div[2]/form/div[1]/div[2]/div/div[2]/ul/li[4]/input"));
element4.sendKeys("/Users/admin/Desktop/NewFolder/463122834.jpg");
2.开源Robot模拟键盘操作
public void CopyClipboardData(HashMap<String, String> params){
String FilePath=params.get("FilePath").toString();
try {
Thread.sleep(1000);
setAndctrlVClipboardData(FilePath);
pressEnterKey();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/*
* 将字符串放到粘贴板中 ;
* */
private void setAndctrlVClipboardData(String string) {
// 声明一个StingSelection 对象,并使用String的参数完成实例化;
StringSelection stringSelection = new StringSelection(string);
// 使用Toolkit对象的setContents将字符串放到粘贴板中 ;
Toolkit.getDefaultToolkit().getSystemClipboard()
.setContents(stringSelection, null);
try {
Robot robot = new Robot();
// 按下crtl v键 ;
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
// 释放crtl v 键
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
} catch (AWTException e) {
System.out.println(e.getStackTrace());
}
}
/**
* 模拟键盘按“Enter”键
* */
private void pressEnterKey() {
try {
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
} catch (AWTException e) {
e.getStackTrace();
}
}
3.Sikuli通过点击图片的方式
import java.io.*;
import org.sikuli.api.*;
import org.sikuli.api.robot.*;
import org.sikuli.api.robot.desktop.*;
public class SikuliUtil {
public static String getSikuliFilePath(String fileName) {
String sikuliPath = getOsName().contains("Windows") ? "\\sikuli\\" : "/sikuli/";
return System.getProperty("user.dir") + sikuliPath + fileName;
}
public static String getOsName() {
return System.getProperties().getProperty("os.name");
}
public static Target with(String imageName) {
return new ImageTarget(new File(getSikuliFilePath(imageName)));
}
public static void waitAndClick(String imageName) {
Target target = with(imageName);
ScreenRegion targetRegion = desktop.wait(target, Timeout);
mouse.click(targetRegion.getCenter());
}
public static void waitAndSendkeys(String imageName, String content) {
Target target = with(imageName);
desktop.wait(target, Timeout);
keyboard.paste(content);
}
static {
desktop = new DesktopScreenRegion();
mouse = new DesktopMouse();
keyboard = new DesktopKeyboard();
}
private static ScreenRegion desktop;
private static Mouse mouse;
private static Keyboard keyboard;
private static int Timeout = 5000;
public static void main(String[] args) {
// click windows start button
SikuliUtil.waitAndClick("1.png");
// click run
SikuliUtil.waitAndClick("2.png");
// send cmd
SikuliUtil.waitAndSendkeys("3.png", "cmd");
// click ok or send key enter
SikuliUtil.waitAndClick("4.png");
}
}
4.通过Autoit脚本生成一个exe,然后调用本地程序
比较简单,可安装AutoIt.ext程序的参考文档
http://www.cnblogs.com/fnng/p/4188162.html
备注:使用第2种和第3种方法远程运行其它机器的时候有点问题