How to save an image using Selenium Webdriver and C#?

I need to save an image on a website using Selenium Webdriver in a C# application, however I am not able to do this. So far the options I found do not work.
Please any solution?
Thanks.
One of the options I tested is using the gravity.code extension

using System.IO;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Extensions;

driver = new ChromeDriver(driverService, opts);
          driver.Navigate().GoToUrl("https://rd1.com.br/fora-da-globo-fausto-silva-recusa-convite-do-canal-para-homenagem/");

          try
          {
             string ImageLink = "//*[@id='post-1163172']/div[8]/ul/li[2]/div[1]/a/img";
             // from element attribute
             var element = driver.FindElement(By.XPath(ImageLink)).DownloadResource(path: @"C:\temp\a.png", attribute: "src");

             // from element text
             var element2 = driver.FindElement(By.XPath(ImageLink)).DownloadResource(path: @"C:\temp\b.png");
          }
          catch (Exception ex)
          {
             Console.WriteLine(ex.Message);
          }

1 answer

  • answered 2021-06-19 22:10 defines

    One way is to use WebClient from the System.Net namespace:

    string ImageLink = "//*[@id='post-1163172']/div[8]/ul/li[2]/div[1]/a/img";
    
    // Find the image element using xpath or other selector
    var element = driver.FindElement(By.XPath(ImageLink));
    
    // Get the value of the src attribute from the image element
    var imageSrc = element.GetAttribute("src");
    
    // Download the image file from the src URI
    using (var client = new System.Net.WebClient())
    {
        client.DownloadFile(imageSrc, @"C:\temp\a.png");
    }
    

    This can be simplified a bit by adding using System.Net; at the top of the file and, if using C# 8 or greater, omitting the braces for the using (var client = new WebClient()) block.