Question

How can I get an image on a webpage with Selenium and encode it to a Base64 string which gets added to a variable? I'm using Selenium C# but any language will probably work.

Was it helpful?

Solution

I am not quite sure what you are asking. What do you mean by "get an image on a webpage"? Do you mean:

  1. grab a screenshot of your page and compare it with some given value? or
  2. take a screenshot of specific element on webpage?
  3. download an image contained in (ie) <img> tag and do something with it?

For taking screenshots, it is widely disucessed here. Although mostly java solutions, they probably could be ported to C# with ease. If what you need is nr 3, then get the URL (ie using xpath //img[@id=\"yourId\"]@src ) and download it using something like WebClient and convert that to base64:

  var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
  var baseString = System.Convert.ToBase64String(plainTextBytes);

OTHER TIPS

This code will helps you, I am using it for my own report, instead of storing report in seperate location, better to convert into base64 form and add it to report.

   String Base64StringofScreenshot="";
    File src = ((TakesScreenshot) driverThread).getScreenshotAs(OutputType.FILE);
    byte[] fileContent = FileUtils.readFileToByteArray(src);
    Base64StringofScreenshot = "data:image/png;base64,"+Base64.getEncoder().encodeToString(fileContent);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top