如何使用Selenium在Internet Explorer中自动上传文件?

时间:2012-05-23 05:53:38

标签: selenium

  

可能重复:
  How to upload a file from a site using Selenium's java inteface

我是Selenium的新手。您能否告诉我如何使用Selenium在Internet Explorer中自动上传文件?

2 个答案:

答案 0 :(得分:4)

这并不容易,而且出于非常好的理由 - 安全性并不容易。如果您能够上传这样的内容,那么什么阻止某人使用相同的方法上传您的详细信息?

您也没有给我们任何使用过的例子:

鉴于此示例网页:

<html>
<head>
<style type="text/css">
.fileSave { color: red; }
</style>
</head>
<label for="fileUpload">File location:
<input type="file" id="fileUpload" />
<br>
<br>
<a href="" class="fileSave">Save file</a>
</body>
</html>

我可以在C#中执行此操作:

Driver = new ChromeDriver();
var fileUploadControl = Driver.FindElement(By.Id("fileUpload"));
fileUploadControl.SendKeys("C:\File.txt");
var submitLink = Driver.FindElement(By.ClassName("fileSave"));
submitLink.Click();

答案 1 :(得分:3)

这已经被问到several times,也在一些Selenium FAQ中。

Selenium 2(WebDriver)Java示例:

// assuming driver is a healthy WebDriver instance
WebElement fileInput = driver.findElement(By.xpath("//input[@type='file']"));
fileInput.sendKeys("C:/path/to/file.jpg");

对于Selenium RC,请参阅this question

我们的想法是直接将文件的绝对路径发送到您通常会单击的元素以获取模态窗口 - 即<input type='file' />元素。