在selenium c#中的下拉列表中截取选项
我想使用selenium c#捕获下拉列表中显示的选项的屏幕截图,就像下面显示的图像一样。
我尝试了多种方法来截取屏幕截图。 基本上我要扩展元素的下拉列表以捕获屏幕截图。 这就是我所做的
//#1 var element = Driver.FindElement(By.Id("carsId")); Actions builder = new Actions(Driver); builder.SendKeys(element, Keys.LeftAlt + Keys.Down).Build().Perform(); //#2 Actions act = new Actions(Driver); act.MoveToElement(element).Build().Perform();
当我在网站上完成但没有通过selenium工作时,按下Alt + Down键的第一个实现工作。 第二个实现也不起作用。 我也尝试过builder.ClickAndHold()
方法。
我在这里还有另一个问题。 是否真的有可能selenium点击并扩展一段时间,直到抓住屏幕?
任何帮助将不胜感激。
我不认为正常下降是可能的。 由于具有您可以选择的选项的叠加显示在本机控件内,并且在selenium可以使用的上下文之外。 为此,您需要一些单独的流程或工具来捕获桌面或应用程序的屏幕截图。
链接
现在,为了捕获桌面/应用程序的屏幕截图,我们在Java中使用Robot对象。
对于C#,您可以使用活动窗口的Capture屏幕截图中建议的方法吗? 。
机器人示例代码:
try { //Get the size of the screen stored in toolkit object Toolkit tk = Toolkit.getDefaultToolkit(); Dimension d = tk.getScreenSize(); //Create Rectangle object using height and width of screen //Here entire screen is captured, change it if you need particular area Rectangle rect = new Rectangle(0, 0, d.width, d.height); //Creates an image containing pixels read from the screen Robot r = new Robot(); BufferedImage img = r.createScreenCapture(rect); //Write the above generated buffered image to a file File f = new File("myimage.jpg"); //Convert BufferedImage to a png/jpg image ImageIO.write(img, "jpg", f); } catch (Exception e) { System.out.println(e.getMessage()); }
这将截取整个屏幕的屏幕截图并将其保存到给定文件位置的文件中。
Selenium只能截取使用Javascript / CSS制作的自定义下拉菜单中的选项,而不是选择下拉列表。
如果上面的代码有效,或者您需要更多帮助,请告诉我。
相信我,没有任何其他工具,它很容易做到。
您只需在单击Select元素后执行以下步骤:
- 制作页面截图
- 获取Select元素位置(页面上的坐标)
- 获取最后一个Option元素位置
- 获取最后一个Option元素大小
-
创建一个新的Rectangle,其位置与select和相同
var screenshotSize = lastOption.Position – Select.Position;
screenShotSize.height + = lastOption.Size.Height;
-
从截图中切除除此Rectangle之外的所有内容
对于c#,您可以使用以下代码#6
Bitmap ScreenshotOfSelect = browserScreenshot.Clone(new Rectangle(point, size), screen.PixelFormat);
因此,您将收到仅包含扩展的Select =)的位图
所以你看,它真的很容易做=)除了selenium之外你不需要任何工具。 此时浏览器窗口也可以隐藏 (例如,在使用phantomJS的情况下)
要打开下拉列表,您只需要.Click()
元素。 所以在你的情况下,
IWebElement element = Driver.FindElement(By.Id("carsId")); element.Click();
将扩大下拉列表。 问题是Selenium的截图function无法捕获打开的下拉列表。 您可以通过使用.NET来获取活动窗口的屏幕截图。 下面的工作示例代码。
static void Main(string[] args) { IWebDriver Driver = new FirefoxDriver(); Driver.Navigate().GoToUrl("http://www.tutorialspoint.com/html/html_select_tag.htm"); Driver.Manage().Window.Maximize(); IWebElement element = Driver.FindElement(By.Name("dropdown")); element.Click(); TakeScreenShotOfWindow(@"C:\sshot.png"); } // from http://sofzh.miximages.com/c%23/ Save the screenshot to the specified path that the user has chosen. bmpScreenshot.Save(filePath, ImageFormat.Png); }