Take screenshot of the options in dropdown in selenium c#

前端 未结 3 1705
隐瞒了意图╮
隐瞒了意图╮ 2021-01-17 11:34

I\'d like to capture the screenshot of the options that are displayed in the dropdown using selenium c# just like the image that is displayed below.

I\'ve t

3条回答
  •  青春惊慌失措
    2021-01-17 11:57

    To open the dropdown you just have to .Click() the element. So in your case,

    IWebElement element = Driver.FindElement(By.Id("carsId"));
    element.Click();
    

    will expand the dropdown. The problem is that Selenium's screenshot functionality does not capture the open dropdown. You can get around that by using .NET to just take a screenshot of the active window. Working example code below.

    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://stackoverflow.com/a/363008/2386774
    public static void TakeScreenShotOfWindow(string filePath)
    {
        // Create a new bitmap.
        var bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb);
    
        // Create a graphics object from the bitmap.
        var gfxScreenshot = Graphics.FromImage(bmpScreenshot);
    
        // Take the screenshot from the upper left corner to the right bottom corner.
        gfxScreenshot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy);
    
        // Save the screenshot to the specified path that the user has chosen.
        bmpScreenshot.Save(filePath, ImageFormat.Png);
    }
    

提交回复
热议问题