selenium文件上传的实现

      一、对于上传文件, 从手动操作我们可以看出, 需要对window 窗体进行操作, 而对于selenium webdriver 在这方面应用就受到了限制。 但是, 庆幸的是, 对于含有input element的上传, 我们可以直接通过sendkeys来传入文件路径,省略了对window 窗体的操作来实现文件上传, 具体实现过程如下:

1)找到上传控件element,并输入路径: 

WebElement element = driver.findElement(By.id("cloudFax-attachment-form-upload-input"));
 element.sendKeys(getFilePath(text.txt));

2)路径的处理:

 private String getFilePath(String resource) {
  URL path = this.getClass().getResource(resource);
  return path.toString().replaceAll("file:/","");
 }

这样把代码和文件上传到服务器, 就可以找到该文件进行上传。

这里需要注意的几点:

  • The element you want to put filepath is the "whole" input element rather than the "readonly" input element,as below, the first locator is right but the second locator will throw an exception.
  • 直接调用element.sendkeys , 不需要再做一次element.clear(),否则会出现该异常:Element must be user-editable in order to clear it.

   二、对于如下控件的上传方式, 暂时无法实现:

 

 

 

 

 

 

 

 

 

posted @ 2014-04-14 20:25  jenniferhuang  阅读(6252)  评论(0编辑  收藏  举报