如何使用selenium webdriver上传文件?

时间:2014-12-09 18:07:21

标签: java firefox selenium selenium-webdriver

我尝试使用selenium网络驱动程序上传文件。浏览文件工作正常。但是当将文件上传到该localhost网站时,我感到很困惑。有一个上传按钮。代码正在跟进。

   <input type="submit" value="Upload" > </input>

我尝试使用以下两个代码。

   driver.findElement(By.name("UNSET FILE NAME")).sendKeys("C:\\Users\\user\\Desktop\\Ontology.owl"); 

   driver.findElement(By.name("Upload")).click();
   driver.findElement(By.id("Upload")).click();

两者都不适合我。提供错误消息时提及的不是该名称或ID。我应该更改以上代码?

Image of interface

3 个答案:

答案 0 :(得分:1)

使用此代码上传并点击“上传”按钮:(假设上传文件的元素是&#39;输入标记&#39;类型&#39;文件&#39;)

driver.findElement(By.xpath("//input[@type='file']")).sendKeys("C:\\Users\\user\\Desktop\\Ontology.owl"); 
driver.findElement(By.xpath("//input[@value='Upload']")).click();

替代: -

以下是上述方法的替代方案。
请仅导入与&#34; java.awt&#34;相关的类。 package,as&#34; Robot,KeyEvent,StringSelection and Toolkit&#34;只会工作

    //Clicking on the Browse button
    driver.findElement(By.xpath("//input[@type='file']")).click();

    //Setting the Clipboard contents
    StringSelection path = new StringSelection("C:\\Users\\user\\Desktop\\Ontology.owl");//the code needed to be pasted in the second dialog box 
    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(path, null);

    Thread.sleep(4000);//Sleep time to detect the window dialog box

    //Pasting the path in the File name field
    Robot robot = new Robot();
    robot.keyPress(KeyEvent.VK_CONTROL);
    robot.keyPress(KeyEvent.VK_V);
    robot.keyRelease(KeyEvent.VK_V);
    robot.keyRelease(KeyEvent.VK_CONTROL);

    //To click the Open button so as to upload file
    robot.keyPress(KeyEvent.VK_ENTER);
    robot.keyRelease(KeyEvent.VK_ENTER);

    //Click on Upload button
    driver.findElement(By.xpath("//input[@value='Upload']")).click();

答案 1 :(得分:0)

使用简单的发送密钥上传

driver.findElement(By.cssSelector("[value='file']")).sendKeys("C:\Users\IEUser\Desktop\Saifurs\Test.html");
driver.findElementBy.cssSelector("[value='Upload']")).click();

答案 2 :(得分:-2)

尝试一次

driver.findElement(By.xpath("input field")).sendKeys("path of the file which u want to upload"); 

输入字段表示xpath的{​​{1}}。