我尝试使用代码上传照片
driver.findElement(By.xpath("xpath")).sendKeys("C:\\Users\\path\\ben.jpg");
但是图片没有上传。
上传按钮的html是
<button id="upfile1" class="buttonclass" style="cursor: pointer" type="button"> Choose Photo</button>
还有其他上传图片的方法吗?我也尝试过使用 WebElement。我需要 JAVA 中的解决方案。
最佳答案
我可以用
driver.findElement(By.id("upfile1")).click();
Thread.sleep(2000);
StringSelection ss = new StringSelection("C:\\Users\\logo1.jpg");
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyRelease(KeyEvent.VK_V);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
但是除了使用机器人之外,还有其他简单的方法可以达到同样的效果吗?
关于testing - 使用 webdriver 上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25074947/