How to upload file in headless browser using robot class in selenium java

浪尽此生 提交于 2019-12-13 18:31:46

问题


How to upload file in headless browser using robot class in selenium java as sendkeys() method not working in my case. I am using firefox and selenium web driver java for my script


回答1:


No need to use Robot class for uploading file using selenium java. Just at first, (1) Upload your files in /tmp folder in case of linux and temp folder in case of windows OS and then, use below code to upload files

String path = FILE_UPLOAD_PATH; 
//(Full path with file name from /tmp folder)
driver.findElement(By.id("FILE_INPUT_ID")).sendKeys(path);

and it will upload file.

Note : Please remove file from /tmp folder after uploading, if no need to free memory.




回答2:


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

setClipboardData(path);
//native key strokes for CTRL, V and ENTER keys

Robot robot = new Robot();
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);

Note: If you are using headless browsers such as chrome or phantomjs, robot class will take the control of present window and send path in it. Also if you use autoIT, script will be waiting for the active window to be appear. so obviously script will be paused and it fails to find the next element.


AutoIT script

WinWaitActive("Open")
Send(@ScriptDir & "\logo.png")
Send("{ENTER}")


来源:https://stackoverflow.com/questions/42129536/how-to-upload-file-in-headless-browser-using-robot-class-in-selenium-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!