【问题标题】:Upload file using C# selenium without SendKeys使用没有 SendKeys 的 C# selenium 上传文件
【发布时间】:2018-06-04 12:13:26
【问题描述】:

我想通过 C# 使用 Selenium Webdriver 上传文件,但 SendKeys 在我的情况下不起作用,因为 HTML 没有输入 type="file"

我可以单击“按钮”并正确打开资源管理器,但之后我无法执行任何操作。 这是要点击的 HTML 区域部分:

<div class="row drop-box cotacao-estudo" ngf-drop="vm.UploadFiles($files, vm.TipoDocumentoEnum.ESTUDO)" ngf-select="vm.UploadFiles($files, vm.TipoDocumentoEnum.ESTUDO)" ngf-change="vm.ValidateFiles($files, $file, $newFiles, $duplicateFiles, $invalidFiles, $event, vm.TipoDocumentoEnum.ESTUDO)" ngf-max-size="30MB" ngf-drag-over-class="'dragover'" ngf-multiple="true" ngf-allow-dir="true" accept="image/gif,image/jpeg,image/jpg,image/tiff,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,image/png,application/pdf,text/plain,application/vnd.ms-excel,application/excel,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/msword" ngf-pattern="'image/gif,image/jpeg,image/jpg,image/tiff,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,image/png,application/pdf,text/plain,application/vnd.ms-excel,application/excel,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/msword'">
    <i class="fa fa-folder fa-3x pull-left" style="color:#5bc0de" aria-hidden="true"></i>
    <label class="pull-left">Estudo *</label>
    <span class="pull-left">Clique para selecionar ou arraste os arquivos aqui</span>
    <div class="progress pull-left ng-hide" ng-show="vm.progressEstudo > 0">
        <div style="width:%;" ng-bind="vm.progressEstudo + '%'" class="ng-binding">%</div>
    </div>
</div>

点击的代码如下:

driver.FindElement(By.XPath("//fieldset[@class='ng-scope']/div[1]/i")).Click();

driver.FindElement(By.ClassName("cotacao-estudo")).Click();

我已经尝试过这段代码但没有成功:

//string filePath = @"C:\Users\cccarvalho\Documents\AUTOMACOES\Estudo.pdf";

String caminho = "//fieldset[@class='ng-scope']/div[1]/i";

document.evaluate('caminho', document, null, 
XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;

String script = "driver.getElementByXpath('caminho').value='" + 
"C:\\\\file.txt" + "';";


((IJavaScriptExecutor)driver).ExecuteScript(script);

【问题讨论】:

  • 点击上传按钮后,windows explorer打开了吗?
  • 你能检查一下 dom,看看你能不能找到一个 input 标签,通过设置 visibility: hiddendisplay: none css 属性来隐藏它?
  • @SaiPawan 是的,win explorer 出现在点击。
  • @GPT14 不,没有任何隐藏元素/标签
  • 在开发控制台中运行$$("input[type='file']")。我的猜测是它就在那里,只是不可见。

标签: c# selenium upload


【解决方案1】:

资源管理器打开后可以发送文件路径如下。

SendKeys.SendWait(@"Path of file");

SendKeys.SendWait(@"{Enter}");

【讨论】:

  • 你必须使用“使用 System.Windows;”
  • 在否决答案之前,请提供正当理由
  • 一旦浏览器窗口不在焦点上,发送密钥将使您的测试失败。这意味着如果窗口被其他窗口最小化、部分或完全覆盖,您的目标窗口将永远不会获得文件路径或回车键。
  • 是的,这将适用于打开的资源管理器弹出窗口。要使用资源管理器上传任何文件,我们必须使用 Sendkeys 或操作类。另一种选择是使用 autoit 自动化资源管理器。
猜你喜欢
  • 2020-10-12
  • 2021-05-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-28
  • 2020-05-09
  • 2020-01-22
相关资源
最近更新 更多