Selenium WebDriver - Upload document to non-input button

后端 未结 1 997
野趣味
野趣味 2020-12-10 19:03

I am needing to upload a document via Selenium WebDriver using Chromedriver. I have tried all the Action class and Javascript stuff, but those do not work. I am assuming the

相关标签:
1条回答
  • 2020-12-10 19:29

    The browser cannot upload a file without an <input> element, unless the file is dropped from the desktop. It would be a security breach to be able to upload a file by code.

    So in your case, the<input> is probably created once the user has clicked the link.

    One way to handle this case is to silence the click event, click the link and then set the file to the <input>:

    // disable the click event on an `<input>` 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 `<input>`
    driver.findElement(By.cssSelector("input[type=file]"))
          .sendKeys("filepath\\Test PDF.pdf");
    

    Note that you may also need to wait for the <input> to be created.

    0 讨论(0)
提交回复
热议问题