如何使用 selenium、python 上传文件(图片)

2022-01-09 00:00:00 python selenium testing file-upload upload

问题描述

如何使用 selenium 测试工具在 web 应用程序上上传图片?我正在使用 python.

How to upload a picture on a web application with the selenium testing tool? I am using python.

我尝试了很多东西,但没有任何效果.

I tried many things, but nothing worked.


解决方案

上传输入控件会打开一个原生对话框(由浏览器完成),因此通过 Selenium 单击控件或浏览按钮只会弹出对话框,测试将挂起.

Upload input control opens a native dialog (it is done by browser) so clicking on the control or browse button via Selenium will just pop the dialog and the test will hang.

解决方法是通过 JavaScript 设置上传输入的值(在 Java 中是通过 JavascriptExecutor 完成的),然后提交表单.

The workaround is to set the value of the upload input via JavaScript (in Java it is done via JavascriptExecutor) and then submit the form.

请参阅 this question 以获取 C# 中的示例,我相信还有一种方法可以调用 JavaScriptPython 但我从未使用过 Selenium Python 绑定

See this question for sample in C#, I am sure there's also a way to call JavaScript in Python but I never used Selenium Python bindings

相关文章