作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我无法使用机器人类和发送 key 上传文件。
下面是我尝试过的代码
package garbage;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class imageupload {
static WebDriver driver;
static String baseURL="http://elance.wetwaresoft.com/account/register";
public static void main(String[] args) throws AWTException, InterruptedException, IOException
{
driver=new FirefoxDriver();
driver.get(baseURL);
WebElement btn=driver.findElement(By.xpath("//*[@class='fileupload-new']"));
btn.click();
System.out.println("Going in Robot class");
Runtime.getRuntime().exec("notepad");
Robot r=new Robot();
r.delay(1000);
r.keyPress(KeyEvent.VK_ENTER);
r.keyPress(KeyEvent.VK_D);
r.keyPress(KeyEvent.VK_SHIFT);
r.keyPress(KeyEvent.VK_SEMICOLON);
r.keyRelease(KeyEvent.VK_SHIFT);
r.keyPress(KeyEvent.VK_BACK_SLASH);
r.keyPress(KeyEvent.VK_A);
r.keyPress(KeyEvent.VK_DOWN);
r.keyPress(KeyEvent.VK_ENTER);
System.out.println("File uploaded");
}
}
当我在记事本中执行机器人类代码时,它会键入路径,但是当我在弹出窗口中执行此代码时,它不会键入任何内容。
如何使用机器人和发送 key 上传文件?
最佳答案
我已使用 Robot 将文件上传逻辑分离到单独的类中,并将方法设为静态。在方法 fileAttachmentUsingRobot
中传递要上传的图像的路径,即图像的完整系统路径。
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.awt.*;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
/**
* Created by ypolshchykau on 30.01.2015.
*/
public class FileAttacherRobotImplementation {
public final static Logger log = LoggerFactory.getLogger(FileAttacherRobotImplementation.class);
/**
* this method implements file attachment using Robot mechanism
*
* @param filePathToImage
*/
public static void fileAttachmentUsingRobot(String filePathToImage) {
Robot robot = null;
try {
robot = new Robot();
} catch (AWTException e) {
e.printStackTrace();
}
setClipboardData(filePathToImage);
robot.delay(1000);
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
}
/**
* method for copying file in order to attach file in File open window
*
* @param str
*/
public static void setClipboardData(String str) {
StringSelection stringSelection = new StringSelection(str);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
}
}
希望这对您有帮助。
关于java - 无法使用机器人类和 Sendkeys 上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28392931/
我有以下正则表达式 /[a-zA-Z0-9_-]/ 当字符串只包含从 a 到z 大小写、数字、_ 和 -。 我的代码有什么问题? 能否请您向我提供一个简短的解释和有关如何修复它的代码示例? //var
我是一名优秀的程序员,十分优秀!