javascript - anchor 标签自动上传文件场景

标签 javascript java selenium

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

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

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

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

最佳答案

您可以尝试以下方法吗?

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")

关于javascript - anchor 标签自动上传文件场景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56112548/

相关文章:

java - 在 Selenium 中自动化时如何禁用 WebDriver 中的 JavaScript?

javascript - FB.XFBML.parse 未捕获 [对象对象]

javascript - 如何使用没有图像的jquery获得圆 Angular 文本框

javascript - 当括号中的变量值破坏我的 addClass 时,jquery 是转义括号

java - 使用 MinMax 和 Alpha-Beta 修剪找到最佳着法

java - Google editboix 给出 InvalidElementStateException :Element is disabled and so may not be used for actions Command duration

javascript - 外部 JavaScript 文件无法识别 HTML 表单

java - 如何在 IntelliJ IDEA 中创建补丁?

java - RCP - 应用程序没有 Activity 窗口

python - 如何使用 Selenium Python 在#shadow-root(打开)中提取信息?