我尝试使用硒将文件上传到网站。站点正在使用"DropzoneJS",女巫删除输入类型="文件"并替换它。
Sourse html code:
<input type="file" id="input-file" name="input-file" value="file">
加载页面后 sourse html 替换:
<div class="dz-message needsclick">
<div class="dropzone-image"></div>
<p class="dropzone-text">Drag and droup you file here <span>or</span></p>
<button class="cta low dropzone-upload-btn" type="button">Upload file</button>
</div>
我尝试设置文件值:
String script = "document.getElementById('input-file').value='" + "D:\\temp\\file.txt" + "';";
((IJavaScriptExecutor)driver).ExecuteScript(script);
但是当然有一个错误(因为id="input-file"替换了输入标签(:
OpenQA.Selenium.WebDriverException: 'javascript error: 无法设置 属性"值"为空
如何上传文件?
更新:
我找到了答案:
如果类型=文件的输入被隐藏,需要找到它。遵循代码帮助我:
var select = Driver.FindElement(By.CssSelector("input[type=file]"));
select.SendKeys("D:\\temp\\file.txt);
我根据上面给出的答案编写了此方法。(感谢您的协助@Dmitry(
public void DropZoneAttachFile(int dropZoneListNumber, string imagePath)
{
//dropZoneListNumber : input[type=file] will return multiple DZ elements if there are more than 1 DZ on a page.
//Figure out what position in the list the DZ you want is and pass the int to this method along with a local image path
IList<IWebElement> dropZoneElement = driver.FindElements((By.CssSelector("input[type=file]")));
dropZoneElement[dropZoneListNumber].SendKeys(imagePath);
}