How to use ScreenshotAsync method of PuppeteerSharp.ElementHandle class

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

Run Puppeteer-sharp automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Program.cs

Source: Program.cs Github

copy
1using AngleSharp;
2using AngleSharp.Dom;
3using AngleSharp.Html.Dom;
4using PuppeteerSharp;
5using PuppeteerSharp.Media;
6using SBClient;
7using System;
8using System.Collections.Generic;
9using System.IO;
10using System.Linq;
11using System.Threading.Tasks;
12
13namespace ConsoleApp2
14{
15    class Program
16    {
17        static async Task Main(string[] args)
18        {
19            await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
20            var browser = await Puppeteer.LaunchAsync(new LaunchOptions
21            {
22                //Headless = false
23            });
24            var page = await browser.NewPageAsync();
25            await page.GoToAsync("https://www.swedishbulls.com/SignalPage.aspx?lang=en&Ticker=8TRA.ST");
26
27            //await page.EvaluateExpressionAsync("document.getElementById('MainContent_uEmail').value = " + "'[email protected]'");
28            //await page.EvaluateExpressionAsync("document.getElementById('MainContent_uPassword').value = " + "'passwörd'");
29            //await page.EvaluateExpressionAsync("document.getElementById('MainContent_btnSubmit').click()");
30            //await page.SetViewportAsync(new ViewPortOptions
31            //{
32            //    Width = 1024,
33            //    Height = 780
34            //});
35
36           
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");
40
41            //await page.ScreenshotAsync("test.png", new ScreenshotOptions
42            //{
43            //    Clip = new Clip()
44            //    {
45            //        X = 10,
46            //        Y = 10,
47            //        Height = 100,
48            //        Width = 100
49            //    }
50            //});
51
52
53           var res=  await page.EvaluateExpressionAsync<string>("document.getElementById('MainContent_signalpagedailycommentarytext').textContent");
54
55            element = await page.QuerySelectorAsync("#MainContent_signalpagedailycommentarytext");
56            var apaaoa = (await element.GetPropertyAsync("textContent")).JsonValueAsync() ;
57            //var res = await element.EvaluateFunctionAsync<string>("textContent");
58
59            await browser.CloseAsync();
60
61
62            //var client = new SwedishBullsClient();
63            ////var s = await client.GetSnapshot("8TRA.ST");
64            ////Console.WriteLine(s.SignalUpdate);
65            ////Console.WriteLine(s.MarketOutlook);
66
67            //await client.Login("[email protected]", "test");
68
69        }
70    }
71
72}
73
Full Screen

PuppeteerHelper.cs

Source: PuppeteerHelper.cs Github

copy
1using System;
2using System.IO;
3using System.Linq;
4using System.Text;
5using System.Threading.Tasks;
6using AngleSharp;
7using AngleSharp.Dom;
8using FrHello.NetLib.Core.Net;
9using PuppeteerSharp;
10
11namespace WebCrawlerFoundation.Helpers
12{
13    public static class PuppeteerHelper
14    {
15        /// <summary>
16        /// 是否已经初始化
17        /// </summary>
18        private static bool _isInit;
19        
20        /// <summary>
21        /// 获取一个浏览器
22        /// </summary>
23        /// <returns></returns>
24        public static async Task<Browser> GetBrowser()
25        {
26            var config = Config.LoadConfig();
27            
28            var launchOptions = new LaunchOptions
29            {
30                Headless = config.HeadLess
31            };
32
33            if (config.RemoteChromePort != 0 && NetHelper.CheckLocalPort(9222))
34            {
35                try
36                {
37                    return await Puppeteer.ConnectAsync(new ConnectOptions { BrowserURL = "http://localhost:9222" });
38                }
39                catch (Exception e)
40                {
41                    Console.WriteLine(e);
42                }
43            }
44
45            await TryInit();
46
47            var browser = await Puppeteer.LaunchAsync(launchOptions);
48            return browser;
49        }
50        
51        /// <summary>
52        /// 截屏保存在当前目录下
53        /// </summary>
54        /// <param name="page">页面</param>
55        /// <returns></returns>
56        public static async Task ScreenshotAsync(this Page page)
57        {
58            var dir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Screenshots");
59
60            if (!Directory.Exists(dir))
61            {
62                Directory.CreateDirectory(dir);
63            }
64            await page.ScreenshotAsync(Path.Combine(dir, $"{DateTime.Now:yyyyMMddhhmmss}.png"));
65        }
66
67        /// <summary>
68        /// 截屏保存在当前目录下
69        /// </summary>
70        /// <param name="elementHandle">界面元素</param>
71        /// <returns></returns>
72        public static async Task ScreenshotAsync(this ElementHandle elementHandle)
73        {
74            var dir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Screenshots");
75
76            if (!Directory.Exists(dir))
77            {
78                Directory.CreateDirectory(dir);
79            }
80            await elementHandle.ScreenshotAsync(Path.Combine(dir, $"{DateTime.Now:yyyyMMddhhmmss}.png"));
81        }
82
83        /// <summary>
84        /// 获取page中的document
85        /// </summary>
86        /// <param name="page"></param>
87        /// <returns></returns>
88        public static async Task<IDocument> GetDocument(Page page)
89        {
90            var config = Configuration.Default.WithDefaultLoader();
91            var context = BrowsingContext.New(config);
92
93            var html = await page.GetContentAsync();
94            var document = await context.OpenAsync(q => q.Content(html));
95
96            return document;
97        }
98
99        /// <summary>
100        /// 根据文件名获取javascript
101        /// </summary>
102        /// <param name="javaScriptName"></param>
103        /// <returns></returns>
104        public static async Task<string> GetJavaScript(string javaScriptName)
105        {
106            var dir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "JsScripts");
107            if (Directory.Exists(dir))
108            {
109                var files = Directory.GetFiles(dir, javaScriptName, SearchOption.AllDirectories);
110                if (files.Any())
111                {
112                    return await File.ReadAllTextAsync(files[0], Encoding.UTF8);
113                }
114            }
115
116            throw new InvalidOperationException($"未找到 {javaScriptName}");
117        }
118
119        /// <summary>
120        /// 用XPath表达式查找
121        /// </summary>
122        /// <param name="page"></param>
123        /// <param name="xpath"></param>
124        /// <param name="timeout"></param>
125        /// <returns></returns>
126        public static async Task<ElementHandle> WaitForXPathAsyncWithOutException(this Page page, string xpath, int timeout = 100)
127        {
128            try
129            {
130                var result = await page.WaitForXPathAsync(xpath, new WaitForSelectorOptions
131                {
132                    Timeout = timeout
133                });
134
135                return result;
136            }
137            // ReSharper disable once EmptyGeneralCatchClause
138            catch (Exception e)
139            {
140            }
141
142            return null;
143        }
144
145        /// <summary>
146        /// 用Selector表达式查找
147        /// </summary>
148        /// <param name="page"></param>
149        /// <param name="selector"></param>
150        /// <param name="timeout"></param>
151        /// <returns></returns>
152        public static async Task<ElementHandle> WaitForSelectorAsyncWithOutException(this Page page, string selector, int timeout = 100)
153        {
154            try
155            {
156                var result = await page.WaitForSelectorAsync(selector, new WaitForSelectorOptions
157                {
158                    Timeout = timeout
159                });
160
161                return result;
162            }
163            // ReSharper disable once EmptyGeneralCatchClause
164            catch (Exception e)
165            {
166            }
167
168            return null;
169        }
170
171        /// <summary>
172        /// 注入JQuery框架
173        /// </summary>
174        /// <param name="page"></param>
175        /// <returns></returns>
176        public static async Task InjectJQuery(this Page page)
177        {
178            await InjectJavascript(page, "https://code.jquery.com/jquery-3.6.0.min.js");
179        }
180
181        public static async Task InjectJavascript(this Page page, string url)
182        {
183            var script =
184                $"var head = document.getElementsByTagName('head')[0];var script = document.createElement('script');script.type = 'text/javascript';script.src = '{url}';head.appendChild(script);";
185
186            await page.EvaluateExpressionAsync(script);
187        }
188        
189        /// <summary>
190        /// 初始化
191        /// </summary>
192        /// <returns></returns>
193        private static async Task TryInit()
194        {
195            if (!_isInit)
196            {
197                ConsoleHelper.Console($"查找chromium版本");
198                await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
199
200                _isInit = true;
201            }
202        }
203    }
204}
Full Screen

ShiftSearchClient.cs

Source: ShiftSearchClient.cs Github

copy
1using PuppeteerSharp;
2using Serilog;
3using System;
4using System.Collections.Generic;
5using System.Globalization;
6using System.IO;
7using System.Linq;
8using System.Text.RegularExpressions;
9using System.Threading;
10using System.Threading.Tasks;
11using ShiftSearch.Code;
12using ShiftSearch.ViewModels;
13
14#nullable enable
15
16namespace ShiftSearch
17{
18    public class ShiftSearchClient : IAsyncDisposable
19    {
20        public ShiftSearchClient(string chromePath)
21        {
22            ChromePath = chromePath;
23        }
24
25        protected string ChromePath { get; }
26        protected Browser? Browser { get; private set; }
27
28        private async Task<string> GetCallAmountString()
29        {
30            string xPath = "//div[@class=\"---ui-lib-Grid-Grid-module__Area\"][contains(@style,'--area-name:callMain')]";
31            return await GetContentOfXpathElement(xPath);
32        }
33
34        private async Task<string> GetPutAmountString()
35        {
36            string xPath = "//div[@class=\"---ui-lib-Grid-Grid-module__Area\"][contains(@style,'--area-name:putMain')]";
37            return await GetContentOfXpathElement(xPath);
38        }
39
40        private async Task<string> GetContentOfXpathElement(string xPath)
41        {
42            var page = await GetPage();
43            Thread.Sleep(1000);
44
45            int attempt = 1;
46            ElementHandle? handle = null;
47            while (handle == null && attempt <= 3)
48            {
49                if (attempt > 1)
50                {
51                    Console.WriteLine( $"Could not find div with xPath {xPath} on page {page.Url}. Trying again: attempt {attempt}");
52                    Thread.Sleep(attempt * 1000);
53                }
54                handle = await GetElement( page, xPath);
55                attempt++;
56            }
57
58            if (handle == null)
59            {
60                Log.Error( $"Could not find div with xPath {xPath} on page {page.Url}!");
61                // TODO Throw exception
62                return "";
63            }
64
65            return await page.EvaluateFunctionAsync<string>("e => e.textContent", handle);
66        }
67
68        protected async Task<ElementHandle?> GetElementWithContent(Page page, string elementType, string content)
69        {
70            string xPathMatch = string.Format("//{0}[contains(., '{1}')]", elementType, content);
71            return await GetElement(page, xPathMatch);
72        }
73
74        public async Task<bool> GoToPage(string url)
75        {
76            Console.WriteLine($"Navigating to page {url}");
77
78            if (Browser == null)
79            {
80                Browser = await StartBrowser();
81            }
82
83            Page page = await GetPage();
84            try
85            {
86                if (page.Url == url)
87                {
88                    await page.ReloadAsync();
89                    return page.Url == url;
90                }
91
92                await page.GoToAsync(url);
93                return page.Url == url;
94            }
95            catch (Exception ex)
96            {
97                Log.Error($"Error loading page {url}, {ex}");
98                return false;
99            }
100        }
101
102        protected async Task<ElementHandle?> GetElement(Page page, string xPathMatch)
103        {
104            ElementHandle[] elementHandles = await page.XPathAsync(xPathMatch);
105
106            List<ElementHandle> visibleHandles = new List<ElementHandle>();
107            foreach (ElementHandle handle in elementHandles)
108            {
109                if (await handle.IsIntersectingViewportAsync())
110                {
111                    visibleHandles.Add(handle);
112                }
113            }
114            if (visibleHandles.Count == 0)
115            {
116                return null;
117            }
118            if (visibleHandles.Count > 1)
119            {
120                Log.Warning(string.Format("Multiple elements found with xPath {0}", xPathMatch));
121            }
122            return visibleHandles[0];
123        }
124
125        protected async Task<Page> GetPage()
126        {
127            #pragma warning disable CS8602 // Dereference of a possibly null reference.
128            Page[] pages = await Browser.PagesAsync();
129            #pragma warning restore CS8602
130            return pages[0];
131        }
132
133        private async Task<Browser> StartBrowser()
134        {
135            Log.Information("Starting headless browser");
136            // This only downloads the browser version if it is has not been downloaded already
137            //await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
138            Browser browser = await Puppeteer.LaunchAsync(new LaunchOptions
139            {
140                Headless = true,
141                ExecutablePath = ChromePath,
142                DefaultViewport = new ViewPortOptions { Width = 2560, Height = 1440 }
143            });
144            return browser;
145        }
146
147        public async Task<BlockOrdersViewModel> RecognizeBlockOrders()
148        {
149            var callAmount = await GetCallAmountString( );
150            var putAmount = await GetPutAmountString( );
151
152            return new BlockOrdersViewModel(callAmount: callAmount, putAmount: putAmount);
153        }
154
155        private async Task TakePieScreenshot(string filePath)
156        {
157            Page page = await GetPage();
158            await page.ScreenshotAsync(filePath,
159                new ScreenshotOptions { Clip = new PuppeteerSharp.Media.Clip { Width = 1000, Height = 1440 } });
160        }
161
162        private static string GetNextScreenshotFilepath()
163        {
164            int current = GetCurrentPieScreenshotNumber();
165            return "C:/Users/Admin/WindowsServices/ShiftSearch/ShiftSearch/screenshots/piecharts/pie-" + current + ".png";
166        }
167
168        private static int GetCurrentPieScreenshotNumber()
169        {
170            Regex reg = new Regex(@"pie-(\d+).png");
171            string[] files = Directory.GetFiles("C:/Users/Admin/WindowsServices/ShiftSearch/ShiftSearch/screenshots/piecharts", "*.png");
172            IEnumerable<string> matches = files.Where(path => reg.IsMatch(path));
173            if (matches.Count() == 0)
174            {
175                return 0;
176            }
177            IEnumerable<int> numbers = matches
178                .Select(path => int.Parse(reg.Match(path).Groups[1].Value));
179            return numbers.Max();
180        }
181
182        public async ValueTask DisposeAsync()
183        {
184            if (Browser != null)
185            {
186                var page = await GetPage();
187                await page.DisposeAsync();
188
189                await Browser.DisposeAsync();
190            }
191        }
192    }
193}
194
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)