Created
March 12, 2019 12:49
-
-
Save kapozade/c907e0a7da9318bf58ed68c35f4bbafb to your computer and use it in GitHub Desktop.
Return screenshot of a page by the help of Selenium. NetCore WebApi code.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Drawing; | |
| using System.IO; | |
| using System.Reflection; | |
| using Microsoft.AspNetCore.Mvc; | |
| using OpenQA.Selenium; | |
| using OpenQA.Selenium.Chrome; | |
| namespace ScreenshotApi.Controllers | |
| { | |
| [Route("api/[controller]")] | |
| [ApiController] | |
| public class ScreenshotController : ControllerBase | |
| { | |
| [HttpGet("screenshot")] | |
| public IActionResult GetScreenshot([FromQuery]string url, [FromQuery]int width = 600, [FromQuery]int height = 600) | |
| { | |
| if (string.IsNullOrWhiteSpace(url)) | |
| return BadRequest(); | |
| try | |
| { | |
| var options = new ChromeOptions(); | |
| options.AddArgument("headless"); | |
| using (var driver = new ChromeDriver(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), | |
| options)) | |
| { | |
| driver.Manage().Window.Size = new Size(width, height); | |
| driver.Navigate().GoToUrl(url); | |
| var screenshotContent = ((ITakesScreenshot)driver).GetScreenshot().AsByteArray; | |
| return File(screenshotContent, "image/jpeg"); | |
| } | |
| } | |
| catch (Exception ex) | |
| { | |
| return StatusCode(500, ex.Message); | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment