Selenium文件上传的实现

发表于:2014-4-17 11:06

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:yansj_scu    来源:51Testing软件测试网采编

  一、对于上传文件, 从手动操作我们可以看出, 需要对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.
  二、对于如下控件的上传方式, 暂时无法实现:
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号