【问题标题】:Selenium WebDriver - Upload document to non-input buttonSelenium WebDriver - 将文档上传到非输入按钮
【发布时间】:2016-10-13 12:30:30
【问题描述】:

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

<a id="Dialogs_Dialogs_lbAttachUpload" onclick="return ButtonVerifyEnabled(this, ShowFileSelect);" class="SkinButton sbBlue" onmouseover="ButtonHover(this,30);" onmouseout="ButtonLeave(this);" onmousedown="ButtonDown(this,30);" onmouseup="ButtonHover(this,30);" skinheight="30" style="color: white; width: 132px; height: 30px; line-height: 30px; background-position: 0px 0px;" title=""><div class="SkinButtonLeft" style="background-position: 0px 0px;"></div><div class="SkinButtonRight" style="background-position: -4px 0px;"></div>Upload documents</a>

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

我最近的尝试是这样的:

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

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

【问题讨论】:

    标签: java selenium


    【解决方案1】:

    浏览器无法上传没有&lt;input&gt; 元素的文件,除非文件从桌面删除。能够通过代码上传文件将是安全漏洞。

    因此,在您的情况下,&lt;input&gt; 可能是在用户单击链接后创建的。

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

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

    请注意,您可能还需要等待 &lt;input&gt; 被创建。

    【讨论】:

      猜你喜欢
      • 2017-12-23
      • 2021-09-26
      • 2015-11-09
      • 2017-02-26
      • 1970-01-01
      • 2018-03-09
      • 2013-09-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多