Selenium WebDriver – 将文档上载到非输入按钮

我需要使用Chromedriver通过Selenium WebDriver上传文档。 我已经尝试了所有的Action类和Javascript的东西,但那些不起作用。 我假设它们不起作用,因为那些依赖于按钮作为输入字段,但是,我正在处理的上传按钮不是。 它的HTML看起来像这样:

Upload documents

我有AutoIT和Sikuli实现和工作,但这些解决方案的问题是我通过Jenkins运行Selenium测试时无法让它们工作。

我最近的尝试看起来像这样:

  WebElement upload = SConfirmOrder.uploadDocuments_btn(driver); Actions actions = new Actions(driver); actions.moveToElement(upload); actions.sendKeys("filepath\\Test PDF.pdf"); 

它成功运行,但实际上没有文档上传。

除非从桌面删除文件,否则浏览器无法在没有元素的情况下上载文件。 能够通过代码上传文件将是一个安全漏洞。

因此,在您的情况下,可能会在用户单击链接后创建

处理此情况的一种方法是使click事件静音,单击链接,然后将文件设置为

 // disable the click event on an `` file ((JavascriptExecutor)driver).executeScript( "HTMLInputElement.prototype.click = function() { " + " if(this.type !== 'file') HTMLElement.prototype.click.call(this); " + "}; " ); // trigger the upload driver.findElement(By.id("Dialogs_Dialogs_lbAttachUpload")) .click(); // assign the file to the `` driver.findElement(By.cssSelector("input[type=file]")) .sendKeys("filepath\\Test PDF.pdf"); 

请注意,您可能还需要等待创建