Search code examples
c#seleniumc#-4.0drop-down-menuscreenshot

Take screenshot of the options in dropdown in selenium c#


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.

enter image description here

I've tried multiple ways to take the screenshot. Basically I've to expand the dropdown of the element to capture the screenshot. Here is what I've done

//#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();

The first implementation to press Alt + Down keys worked manually when I've done on the site but didn't work through selenium. The second implementation didn't work either. I've also tried builder.ClickAndHold() method as well.

And I've another question over here. Is it really possible for selenium to click and expand for a while until to grab the screen?

Any help would be greatly appreciated.


Solution

  • I don't think it'll be possible for normal drop downs. Since the overlay with the options you can choose from are displayed inside a native control and outside of the context of what selenium can work with. For this, you'll need some separate process or tool that can capture the screenshot of the desktop or application it self.

    Link

    Now, to capture the screenshot of desktop/application, we use Robot objects in Java.

    For C#, you can use methods suggested in Capture screenshot of active window?.

    Robot Sample Code:

    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());
    }
    

    This will take the screenshot of the entire screen and save it into the file on given file location.

    Selenium can only take screenshot of options in custom dropdowns made using Javascript/CSS and not in select dropdown.

    Let me know if above code works or you need more help.