问题
I am writing a script in selenium using webdriver and nunit to automate my web application. I have to upload file in my application. But unable to do it.
The dialog opens while browse button is clicked, and upon selecting file the file is uploaded.
Browse
How can i do it in selenium?
回答1:
Answer is already available on stack, still I am repeating:
find the upload button, create webelement of this and follow this code:
//open upload window
upload.click();
//put path to your image in a clipboard
StringSelection ss = new StringSelection(<give file location>);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
//imitate mouse events like ENTER, CTRL+C, CTRL+V
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_ENTER);
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.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
回答2:
public void uploadFile(String locatorId, String filePath) {
WebElement fileInput = findElementExplicitWaitWithNoVisbility(By.id(locatorId), true);
fileInput.clear();
fileInput.sendKeys(filePath);}
来源:https://stackoverflow.com/questions/32760330/how-to-handle-file-upload-in-selenium-in-windows-7