如何在 Selenium 中使用 Windows 上传对话框处理文件上传

How to handle upload of file using Windows Upload Dialog in Selenium

我正在尝试使用 Selenium (C#) 上传附件。

检查站点的 DOM 后,我注意到附加文件的 link 正在使用 object tags。 以下是 HTML 摘录:

<object id="ctl00_mainContent_rauFilessilverlight03" class="ruObject" height="22px" type="application/x-silverlight-2" data="data:application/x-silverlight-2," style="width: 100%;"> 
 <param value="/App/somelongjunkyparameters" name="source"/> 
 <param value="true" name="windowless"/> <param value="transparent" name="background"/> 
 <param value="some number" name="minRuntimeVersion"/> 
 <param value="PostData=anotherlongjunkyparameters,SilverlightRowId=ctl00_mainContent_rauFilessilverlight03,AsyncUploadId=ctl00_mainContent_rauFiles,MultipleSelection=Disabled,AllowedFileExtensions=,ServiceHandlerUrl=/App/Telerik.Web.UI.WebResource type=rau,MaxFileSize=0" name="InitParams"/> 
 <param value="true" name="autoUpgrade"/> 
</object>

到目前为止我已经试过了:

IWebElement fileAttachTA = driver.FindElement(By.XPath("//object[@class='ruObject']"));
fileAttachTA.Click();
String filePath = "C:/User/My Documents/file.txt";

Selenium 能够找到对象,但是,我是否应该切换到 Windows 上传对话框? 希望听到任何有这方面经验的人的意见。

谢谢!

开发该网站的人使用的是非标准机制来上传文件。查看您提供的 HTML,它看起来像某种 Silverlight 控件。当页面使用标准 HTML 上传机制(即 <input type="file"> 元素)时,Selenium WebDriver 可以正确处理用于上传文件的文件选择对话框,但它没有希望使用非-标准上传机制。您需要找到一种方法来处理 Selenium 之外的对话框。

我在 downloading/uploading 文件时与 Windows 对话框对话时遇到问题。我的解决方案是利用 user32.dll GetForegroundWindow()。然后根据 header 文本(仍然使用 user32.dll)创建了一些等待对话框出现消失的方法。然后最后创建一个 BeginInvoke 动作,等待 window 弹出,然后继续发送键。现在我面前没有代码示例,但是 Google user32.dll Selenium,您会得到一些信息。

我明白了,我所做的是:

 IWebElement fileAttachTA = driver.FindElement(By.XPath("//object[@class='ruObject']"));
     fileAttachTA.Click();

     //Switch into the windows upload dialog
     SendKeys.SendWait("^a");
     Thread.Sleep(1000);
     SendKeys.SendWait(file);
     Thread.Sleep(1000);
     SendKeys.SendWait(@"{Enter}");
     Thread.Sleep(1000);

我使用 System.Windows.Forms 让 SendKeys.SendWait 工作。谢谢大家!