How to use ScreenshotAsync method of PuppeteerSharp.ElementHandle class

Best Puppeteer-sharp code snippet using PuppeteerSharp.ElementHandle.ScreenshotAsync

ElementHandle.cs

Source:ElementHandle.cs Github

copy

Full Screen

...39 /// <returns>The task</returns>40 /// <param name="file">The file path to save the image to. The screenshot type will be inferred from file extension. 41 /// If path is a relative path, then it is resolved relative to current working directory. If no path is provided, 42 /// the image won't be saved to the disk.</param>43 public Task ScreenshotAsync(string file) => ScreenshotAsync(file, new ScreenshotOptions());44 /// <summary>45 /// This method scrolls element into view if needed, and then uses <seealso cref="Page.ScreenshotDataAsync(ScreenshotOptions)"/> to take a screenshot of the element. 46 /// If the element is detached from DOM, the method throws an error.47 /// </summary>48 /// <returns>The task</returns>49 /// <param name="file">The file path to save the image to. The screenshot type will be inferred from file extension. 50 /// If path is a relative path, then it is resolved relative to current working directory. If no path is provided, 51 /// the image won't be saved to the disk.</param>52 /// <param name="options">Screenshot options.</param>53 public async Task ScreenshotAsync(string file, ScreenshotOptions options)54 {55 if (!options.Type.HasValue)56 {57 options.Type = ScreenshotOptions.GetScreenshotTypeFromFile(file);58 }59 var data = await ScreenshotDataAsync(options).ConfigureAwait(false);60 using (var fs = AsyncFileHelper.CreateStream(file, FileMode.Create))61 {62 await fs.WriteAsync(data, 0, data.Length).ConfigureAwait(false);63 }64 }65 /// <summary>66 /// This method scrolls element into view if needed, and then uses <seealso cref="Page.ScreenshotDataAsync(ScreenshotOptions)"/> to take a screenshot of the element. 67 /// If the element is detached from DOM, the method throws an error....

Full Screen

Full Screen

PuppeteerHelper.cs

Source:PuppeteerHelper.cs Github

copy

Full Screen

...48 /// 截屏保存在当前目录下49 /// </summary>50 /// <param name="page">页面</param>51 /// <returns></returns>52 public static async Task ScreenshotAsync(this Page page)53 {54 var dir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Screenshots");55 if (!Directory.Exists(dir))56 {57 Directory.CreateDirectory(dir);58 }59 await page.ScreenshotAsync(Path.Combine(dir, $"{DateTime.Now:yyyyMMddhhmmss}.png"));60 }61 /// <summary>62 /// 截屏保存在当前目录下63 /// </summary>64 /// <param name="elementHandle">界面元素</param>65 /// <returns></returns>66 public static async Task ScreenshotAsync(this ElementHandle elementHandle)67 {68 var dir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Screenshots");69 if (!Directory.Exists(dir))70 {71 Directory.CreateDirectory(dir);72 }73 await elementHandle.ScreenshotAsync(Path.Combine(dir, $"{DateTime.Now:yyyyMMddhhmmss}.png"));74 }75 /// <summary>76 /// 获取page中的document77 /// </summary>78 /// <param name="page"></param>79 /// <returns></returns>80 public static async Task<IDocument> GetDocument(Page page)81 {82 var config = Configuration.Default.WithDefaultLoader();83 var context = BrowsingContext.New(config);84 var html = await page.GetContentAsync();85 var document = await context.OpenAsync(q => q.Content(html));86 return document;87 }...

Full Screen

Full Screen

ShiftSearchClient.cs

Source:ShiftSearchClient.cs Github

copy

Full Screen

...133 }134 private async Task TakePieScreenshot(string filePath)135 {136 Page page = await GetPage();137 await page.ScreenshotAsync(filePath,138 new ScreenshotOptions { Clip = new PuppeteerSharp.Media.Clip { Width = 1000, Height = 1440 } });139 }140 private static string GetNextScreenshotFilepath()141 {142 int current = GetCurrentPieScreenshotNumber();143 return "C:/Users/Admin/WindowsServices/ShiftSearch/ShiftSearch/screenshots/piecharts/pie-" + current + ".png";144 }145 private static int GetCurrentPieScreenshotNumber()146 {147 Regex reg = new Regex(@"pie-(\d+).png");148 string[] files = Directory.GetFiles("C:/Users/Admin/WindowsServices/ShiftSearch/ShiftSearch/screenshots/piecharts", "*.png");149 IEnumerable<string> matches = files.Where(path => reg.IsMatch(path));150 if (matches.Count() == 0)151 {...

Full Screen

Full Screen

PelikanReceiver.cs

Source:PelikanReceiver.cs Github

copy

Full Screen

...115 }116 catch (Exception ex)117 {118 Console.WriteLine(ex.GetError());119 await page.ScreenshotAsync("PelikanScreenshot.jpg");120 result = "";121 // because i don't know how else to do it122 }123 finally124 {125 //var elements = document.getElementsByClassName("Journey-overview Journey-return")126 //for(i = 0; i < elements.length; i++) {elements[i].click();}127 }128 129 }130 }131 return result;132 }133 }...

Full Screen

Full Screen

Renderer.cs

Source:Renderer.cs Github

copy

Full Screen

...38 var page = await GetPageAsync( browser, o );39 40 var panel = await GetPanelAsync( page, o );4142 await panel.ScreenshotAsync( o.FileName );43 Logger.Debug( $"Rendeting complete: {o.FileName}" );44 }45 catch( Exception e )46 {47 Logger.Error( $"Rendering failed. {e.Message}" );4849 await RenderEmbeddedImage( o, "rendering_error" );50 //TASKKILL /IM chrome.exe /F51 }52 finally53 {54 await browser?.CloseAsync();55 }56 } ...

Full Screen

Full Screen

WebPageService.cs

Source:WebPageService.cs Github

copy

Full Screen

...70 }71 public async Task<string> TakeScreenshot()72 {73 var screenshotPath = GetTempFilePathWithExtension(".jpg");74 await _page.ScreenshotAsync(screenshotPath, new ScreenshotOptions()75 {76 Quality = 95,77 // FullPage = true,78 Type = ScreenshotType.Jpeg79 });80 // Base64PageScreenshot = Convert.ToBase64String(File.ReadAllBytes(screenshotPath));81 PathToScreenshot = screenshotPath;82 return PathToScreenshot;83 }84 public static SelectorType GetSelectorType(string selector)85 {86 SelectorType sel = SelectorType.Unspecified;87 try88 {...

Full Screen

Full Screen

Chromium.cs

Source:Chromium.cs Github

copy

Full Screen

...16 Width = Convert.ToInt32 (Math.Max (page.Viewport.Width, Math.Ceiling (bounding_box.Width))),17 Height = Convert.ToInt32 (Math.Max (page.Viewport.Height, Math.Ceiling (bounding_box.Height))),18 });19 ElementHandle element = await page.WaitForSelectorAsync (selector);20 await element.ScreenshotAsync (pathFilePNG);21 await element.DisposeAsync ();22 log.LogInformation ("End - ScreenshotSelectorAsync()");23 } catch (Exception ex) {24 log.LogError ("Erro: {0}", ex.Message);25 }26 }27 public async Task InputSelectorAsync (Page page, string selector, string dataInput, ILogger log) {28 try {29 log.LogInformation ("Begin - InputSelectorAsync()");30 await page.WaitForSelectorAsync (selector);31 await page.FocusAsync (selector);32 await page.Keyboard.TypeAsync (dataInput);33 log.LogInformation ("End - InputSelectorAsync()");34 } catch (Exception ex) {...

Full Screen

Full Screen

Program.cs

Source:Program.cs Github

copy

Full Screen

...3536 37 var element = await page.QuerySelectorAsync("#MainContent_ASPxRoundPanel2_WebChartControl1_IMG");38 //var element = await page.EvaluateExpressionAsync<ElementHandle>("document.getElementById('MainContent_ASPxRoundPanel2_WebChartControl1_IMG')");39 await element.ScreenshotAsync("gurka.png");4041 //await page.ScreenshotAsync("test.png", new ScreenshotOptions42 //{43 // Clip = new Clip()44 // {45 // X = 10,46 // Y = 10,47 // Height = 100,48 // Width = 10049 // }50 //});515253 var res= await page.EvaluateExpressionAsync<string>("document.getElementById('MainContent_signalpagedailycommentarytext').textContent");5455 element = await page.QuerySelectorAsync("#MainContent_signalpagedailycommentarytext"); ...

Full Screen

Full Screen

ScreenshotAsync

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static async Task Main(string[] args)7 {8 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);9 using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false }))10 using (var page = await browser.NewPageAsync())11 {12 await page.ScreenshotAsync("google.png");13 var elementHandle = await page.QuerySelectorAsync("img");14 await elementHandle.ScreenshotAsync("google-logo.png");15 }16 }17 }18}

Full Screen

Full Screen

ScreenshotAsync

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static async Task Main(string[] args)7 {8 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);9 using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true }))10 {11 using (var page = await browser.NewPageAsync())12 {13 var element = await page.QuerySelectorAsync("#hplogo");14 await element.ScreenshotAsync("1.png");15 }16 }17 }18 }19}20using System;21using System.Threading.Tasks;22using PuppeteerSharp;23{24 {25 static async Task Main(string[] args)26 {27 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);28 using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true }))29 {30 using (var page = await browser.NewPageAsync())31 {32 await page.ScreenshotAsync("2.png");33 }34 }35 }36 }37}38using System;39using System.Threading.Tasks;40using PuppeteerSharp;41{42 {43 static async Task Main(string[] args)44 {45 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);46 using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true }))47 {48 using (var page = await browser.NewPageAsync())49 {50 await browser.ScreenshotAsync("3.png");51 }52 }53 }54 }55}56using System;57using System.Threading.Tasks;58using PuppeteerSharp;59{

Full Screen

Full Screen

ScreenshotAsync

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static async Task Main(string[] args)7 {8 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);9 var browser = await Puppeteer.LaunchAsync(new LaunchOptions10 {11 Args = new string[] { "--no-sandbox" }12 });13 var page = await browser.NewPageAsync();14 var elementHandle = await page.QuerySelectorAsync("input[name='q']");15 var screenshot = await elementHandle.ScreenshotAsync();16 await page.ScreenshotAsync("screenshot.png");17 await browser.CloseAsync();18 }19 }20}

Full Screen

Full Screen

ScreenshotAsync

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static async Task Main(string[] args)7 {8 var options = new LaunchOptions { ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" };9 using (var browser = await Puppeteer.LaunchAsync(options))10 {11 using (var page = await browser.NewPageAsync())12 {13 var element = await page.QuerySelectorAsync("input[name='q']");14 await element.ScreenshotAsync("element.png");15 }16 }17 }18 }19}

Full Screen

Full Screen

ScreenshotAsync

Using AI Code Generation

copy

Full Screen

1var page = await browser.NewPageAsync();2await page.ScreenshotAsync("google.png");3await page.CloseAsync();4var page = await browser.NewPageAsync();5await page.ScreenshotAsync("google.png");6await page.CloseAsync();7var page = await browser.NewPageAsync();8await page.ScreenshotAsync("google.png");9await page.CloseAsync();10var page = await browser.NewPageAsync();11await page.ScreenshotAsync("google.png");12await page.CloseAsync();13var page = await browser.NewPageAsync();14await page.ScreenshotAsync("google.png");15await page.CloseAsync();16var page = await browser.NewPageAsync();17await page.ScreenshotAsync("google.png");18await page.CloseAsync();

Full Screen

Full Screen

ScreenshotAsync

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static void Main(string[] args)7 {8 MainAsync().Wait();9 }10 static async Task MainAsync()11 {12 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);13 using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false }))14 using (var page = await browser.NewPageAsync())15 {16 await page.GoToAsync("

Full Screen

Full Screen

ScreenshotAsync

Using AI Code Generation

copy

Full Screen

1var page = await browser.NewPageAsync();2var elementHandle = await page.QuerySelectorAsync("input[name='q']");3await elementHandle.ScreenshotAsync("screenshot.png");4await page.CloseAsync();5var page = await browser.NewPageAsync();6await page.ScreenshotAsync("screenshot.png");7await page.CloseAsync();8var page = await browser.NewPageAsync();9await browser.ScreenshotAsync("screenshot.png");10await page.CloseAsync();11var page = await browser.NewPageAsync();12await page.EvaluateFunctionAsync("() => document.body.style.border = '5px solid red'");13await browser.ScreenshotAsync("screenshot.png");14await page.CloseAsync();15var page = await browser.NewPageAsync();16await page.EvaluateFunctionAsync("() => document.body.style.border = '5px solid red'");17await page.ScreenshotAsync("screenshot.png");18await page.CloseAsync();19var page = await browser.NewPageAsync();20await page.EvaluateFunctionAsync("() => document.body.style.border = '5px solid red

Full Screen

Full Screen

ScreenshotAsync

Using AI Code Generation

copy

Full Screen

1using System;2using System.IO;3using System.Threading.Tasks;4using PuppeteerSharp;5{6 {7 static async Task Main(string[] args)8 {9 var browser = await Puppeteer.LaunchAsync(new LaunchOptions10 {11 });12 var page = await browser.NewPageAsync();13 var elementHandle = await page.QuerySelectorAsync("div");14 var screenshot = await elementHandle.ScreenshotAsync();15 File.WriteAllBytes("screenshot.png", screenshot);16 await browser.CloseAsync();17 }18 }19}20using System;21using System.IO;22using System.Threading.Tasks;23using PuppeteerSharp;24{25 {26 static async Task Main(string[] args)27 {28 var browser = await Puppeteer.LaunchAsync(new LaunchOptions29 {30 });31 var page = await browser.NewPageAsync();32 var screenshot = await page.ScreenshotAsync();33 File.WriteAllBytes("screenshot.png", screenshot);34 await browser.CloseAsync();35 }36 }37}38using System;39using System.IO;40using System.Threading.Tasks;41using PuppeteerSharp;42{43 {44 static async Task Main(string[] args)45 {46 var browser = await Puppeteer.LaunchAsync(new LaunchOptions47 {48 });49 var page = await browser.NewPageAsync();

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful