如何在不使用sendkey的情况下从窗口弹出菜单中从本地计算机中选择Selenium Webdriver中的文件 [英] How to select file in selenium webdriver from local machine from window popup without using sendkeys
问题描述
我需要从本地计算机中的Selenium Webdriver中选择一个文件,但是由于Selenium仅支持Web,所以我无法从本地计算机(Window Poup)中选择文件,因为它没有任何路径可以填充通过sendkeys的文件的路径.是否有我可以从窗口中选择文件的任何解决方案(使用机器人类或autoIT工具或任何其他解决方案).我已经研究过autoIt工具,但没有足够的细节来实施,如果有人知道它,请对此进行答复.请找到随附的屏幕截图以供参考.
I need to select a file in selenium webdriver from local machine, but as selenium only supports web so I am not able to select file from local machine(Window poup) as it is not having any path in which I can fill the path of file through sendkeys. Is there any solution(using robotics class or autoIT tool or any other solution) from which I can able to select file from window. I have looked into autoIt tool but have not got enough details to implement, if anybody knows about it please reply on this. Please find attached screenshot for reference.
推荐答案
我使用了Robot类,这比使用AutoIT工具要容易得多.请找到以下代码:
I have used Robot class and this is much more easy than using AutoIT tool. Please find below code:
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
public void testUpload() throws InterruptedException
{
WebElement element = driver.findElement(By.name("uploadfilebutton"));
//can use By cssSelector or name (path) as per convenience
element.click();
uploadFile("path to the file");
Thread.sleep(2000);
}
/**
* This method will set any parameter string to the system's clipboard.
*/
public static void setClipboardData(String string) {
//StringSelection is a class that can be used for copy and paste operations.
StringSelection stringSelection = new StringSelection(string);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
}
public static void uploadFile(String fileLocation) {
try {
//Setting clipboard with file location
setClipboardData(fileLocation);
//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);
} catch (Exception exp) {
exp.printStackTrace();
}
}
这篇关于如何在不使用sendkey的情况下从窗口弹出菜单中从本地计算机中选择Selenium Webdriver中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!