简体   繁体   English

使用webdriver上传文件

[英]Upload file using webdriver

I have tried to upload a photo using the code 我尝试使用代码上传照片

driver.findElement(By.xpath("xpath")).sendKeys("C:\\Users\\path\\ben.jpg");

But the image is not getting uploaded. 但是图像没有被上传。

The html of the upload button is 上传按钮的html是

<button id="upfile1" class="buttonclass" style="cursor: pointer" type="button"> Choose Photo</button>

Is there any other way to upload image. 还有其他上传图片的方法。 I have tried using WebElement also. 我也尝试过使用WebElement。 I need a solution in JAVA. 我需要使用JAVA解决方案。

I was able to do it using 我能够使用

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);

But is there any other simple methods to achieve the same other than using robot? 但是,除了使用机器人之外,还有其他简单的方法可以实现相同目的吗?

Add System.Windows.Forms reference and try the below code. 添加System.Windows.Forms参考,然后尝试以下代码。

driver.findElement(By.Id("upfile1")).Click();
System.Windows.Forms.SendKeys.SendWait("C:\\Users\\path\\ben.jpg");
System.Windows.Forms.SendKeys.SendWait("{ENTER}");

出现的弹出窗口是一个Windows窗口,应使用AutoIT处理。

If you are using RemoteWebDriver , then you need to use LocalFileDector to upload the file to the remote selenium server first. 如果使用RemoteWebDriver ,则需要使用LocalFileDector首先将文件上传到远程RemoteWebDriver服务器。 And then use the remote path to upload from the remote selenium server. 然后使用远程路径从远程Selenium服务器上载。

driver.setFileDetector(new LocalFileDetector());
driver.findElement(By.xpath("xpath")).sendKeys("C:\\Users\\path\\ben.jpg");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何处理 Selenium WebDriver 中的文件上传元素? - How to handle file upload element in Selenium WebDriver? 如何在没有“输入”元素的情况下在 Selenium WebDriver 中上传文件 - How to upload a file in Selenium WebDriver with no 'input' element 无需任何输入即可使用selenide webdriver上传文件 - Upload file with selenide webdriver without any input 文件上传文件名文本仅在 Selenium Webdriver 会话期间溢出,阻止上传按钮 - File upload filename text overflows only during Selenium Webdriver session, blocking the upload button 如何使用量角器将文件上传到ng-file-upload元素 - How to upload file using Protractor to the ng-file-upload element 如何使用watir-webdriver打开zip文件? - How do you open a zip file using watir-webdriver? TestCafe:无法使用单步上传控件上传文件 - TestCafe: Unable to upload file using single step upload control 使用 Tosca Testsuite 选择和上传文件 - Select and upload file using Tosca Testsuite 如何使用katalon studio上传文件/照片? - How to upload a file/photo using katalon studio? 如何使用JMeter在JSF应用程序中上传文件 - How to upload file in a JSF application using JMeter
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM