首页 > 解决方案 > 锚标签自动上传文件场景

问题描述

我正在尝试使用不同的断言组合来自动化具有与文件上传相关的多个场景的行为。UI中有一个锚标记而不是输入标记,为什么我不能使用发送键来上传文件。我不想使用 AutoIT、Sikuli 之类的工具,因为它们与云环境上的远程执行不兼容,并增加了额外的库负债。

这是一个 Angular js 应用程序,DOM 代码是

---"a href="javascript:void(0)" title="选择要上传的文件" class="btn btn-blue" ng-show="fileUploadSubmitted" id="file_input_btn" ng-click="uploadFileAttachment( ) "

我试图找到:- 1:Angular js库的任何内置上传功能,以便我可以通过javascript执行器执行它。2:Sikuli 和 AutoIt 正在工作,但那将是最后一个解决方案 3:尝试编辑标签名称以输入 DOM 中的类型文件,然后是 sendkeys,但它不起作用

标签: javascriptjavaselenium

解决方案


您可以尝试以下方法。

Tested locally not on the server.

# get the button element
ele = driver.find_element_by_id("file_input_btn")
# add a hidden file input ( might have to change the onchange event based on the events associated to the button in above line as you don't have a form)
driver.execute_script("var x=  document.createElement('INPUT');x.setAttribute('type', 'file'); x.setAttribute('onchange','this.form.submit()');x.setAttribute('hidden', 'true'); arguments[0].appendChild(x);",ele)
# send the file path here ( this should upload the file)
driver.find_element_by_xpath("//input[@type='file']").send_keys("file path should go here")

推荐阅读