【问题标题】:Selenium and C#: Unable to open File Upload dialog with buttonSelenium 和 C#:无法使用按钮打开文件上传对话框
【发布时间】:2017-10-26 08:17:17
【问题描述】:

我有一个包含文本、文本字段、普通表单按钮和文件上传按钮(打开文件上传对话框)的页面。

所有其他元素都可以访问,除了文件上传按钮。我已经尝试过 .Click() 和 JavaScriptExecutor,但据我所知(视觉上)文件对话框永远不会打开。但是没有错误消息。

页面来源:

<a class="bttngrey file-input-container bttn-small" data-bind="enable: !uploading() " style="margin-top: 10px; ... data-original-title="Add attachment">
   <i class="fa fa-cloud-upload">...</i>
     <input type="file" data-bind="upload: addAttachments, enable: !uploading()"> == $9

点击按钮的 C#/Selenium 代码:​​

注意:我使用 Button 类和 JavaScriptActions 类来处理对 ChromeDriver 实例的调用,而不是直接调用它。我希望代码 sn-ps 有意义。

Button.FindByXPath("/html/body/div[1]/div[2]/overlay--master/div/div/overlay-lightbox/div/div[3]/content-placeholder/a").Click();

JavaScriptActions.ButtonClickXPath("/html/body/div[1]/div[2]/overlay--master/div/div/overlay-lightbox/div/div[3]/content-placeholder/a");

public class Button {
    public static IWebElement FindByXPath (string bttnxpath) {
        return GCDriver.Instance.FindElement(By.XPath(bttnxpath));
    }
}

public class JavascriptActions {
    public static void ButtonClickXPath (string xpath) {
        GCDriver.JSClickXPath(xpath);
    }
}

public class GCDriver {
    ....
    ....
    ....
    public static void JSClickXPath (string xpath) {
        IWebElement icon = Instance.FindElement(By.XPath(xpath));
        Actions ob = new Actions(Instance);
        ob.Click(icon);
        IAction action = ob.Build();
        action.Perform();
    }
    ....
    ....
    ....
}

点击按钮的方法似乎都不起作用。即使它们适用于页面上的其他“正常”按钮。我尝试 JavaScriptExecutor 的原因是我之前遇到过这样的情况,即像这样的按钮(打开文件对话框)不能通过普通的 Selenium 方法点击,但它是用 JavaScriptExecutor 实现的。

这里奇怪的是这两种方法都刚刚完成而没有任何错误。但是,当我查看页面时,我看不到单击和打开对话框。测试立即结束。在单击按钮之前和之后添加显式等待也无济于事。

有什么想法吗?如有必要,我会详细说明;并不总是很清楚需要显示多少代码才能使问题/问题清晰。

【问题讨论】:

    标签: c# selenium


    【解决方案1】:

    请尝试以下代码,在我的项目中使用类似的代码:

    IWebElement element = new WebDriverWait(_browserWindow, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.CssSelector("[class='fa fa-cloud-upload']")));

    //发送完整的文件路径来附加它

    element.SendKeys("文件路径");

    此外,根据发布的 HTML 代码,上传按钮包含复合类名称。因此,请参阅此组合类元素定位器: Compound class names are not supported. Consider searching for one class name and filtering the results

    【讨论】:

    【解决方案2】:

    试试这个:(使用驱动程序类实例)

    Actions actions = new Actions(Driver.Instance);
    actions.MoveToElement(Driver.Instance.FindElement(By.XPath(xpath)));
    actions.Click();
    actions.Build().Perform();
    

    只需在驱动程序类中创建一个方法,然后从代码中的相关位置调用它。

    您可以使用 SendKeys 发送文件路径,但我通常使用 AutoIt 库来处理窗口上的操作,因为它不是浏览器/Web 元素。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-07
      • 1970-01-01
      • 2016-03-14
      • 2016-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多