How to use Tracing class of PuppeteerSharp package

Best Puppeteer-sharp code snippet using PuppeteerSharp.Tracing

CDPSession.cs

Source:CDPSession.cs Github

copy

Full Screen

...77        public event EventHandler<MessageEventArgs> MessageReceived;78        /// <summary>79        /// Occurs when tracing is completed.80        /// </summary>81        public event EventHandler<TracingCompleteEventArgs> TracingComplete;82        /// <summary>83        /// Occurs when the connection is closed.84        /// </summary>85        public event EventHandler Closed;86        /// <summary>87        /// Gets or sets a value indicating whether this <see cref="CDPSession"/> is closed.88        /// </summary>89        /// <value><c>true</c> if is closed; otherwise, <c>false</c>.</value>90        public bool IsClosed { get; internal set; }91        /// <summary>92        /// Gets the logger factory.93        /// </summary>94        /// <value>The logger factory.</value>95        public ILoggerFactory LoggerFactory { get; }96        #endregion97        #region Public Methods98        internal void Send(string method, dynamic args = null)99            => _ = SendAsync(method, args, false);100        /// <summary>101        /// Protocol methods can be called with this method.102        /// </summary>103        /// <param name="method">The method name</param>104        /// <param name="args">The method args</param>105        /// <returns>The task.</returns>106        public async Task<T> SendAsync<T>(string method, dynamic args = null)107        {108            JObject content = await SendAsync(method, args).ConfigureAwait(false);109            return content.ToObject<T>();110        }111        /// <summary>112        /// Protocol methods can be called with this method.113        /// </summary>114        /// <param name="method">The method name</param>115        /// <param name="args">The method args</param>116        /// <param name="waitForCallback">117        /// If <c>true</c> the method will return a task to be completed when the message is confirmed by Chromium.118        /// If <c>false</c> the task will be considered complete after sending the message to Chromium.119        /// </param>120        /// <returns>The task.</returns>121        /// <exception cref="PuppeteerSharp.PuppeteerException"></exception>122        public async Task<JObject> SendAsync(string method, dynamic args = null, bool waitForCallback = true)123        {124            if (Connection == null)125            {126                throw new PuppeteerException($"Protocol error ({method}): Session closed. Most likely the {TargetType} has been closed.");127            }128            var id = Interlocked.Increment(ref _lastId);129            var message = JsonConvert.SerializeObject(new Dictionary<string, object>130            {131                { MessageKeys.Id, id },132                { MessageKeys.Method, method },133                { MessageKeys.Params, args }134            });135            _logger.LogTrace("Send ► {Id} Method {Method} Params {@Params}", id, method, (object)args);136            MessageTask callback = null;137            if (waitForCallback)138            {139                callback = new MessageTask140                {141                    TaskWrapper = new TaskCompletionSource<JObject>(),142                    Method = method143                };144                _callbacks[id] = callback;145            }146            try147            {148                await Connection.SendAsync(149                    "Target.sendMessageToTarget", new Dictionary<string, object>150                    {151                        {"sessionId", SessionId},152                        {"message", message}153                    },154                    waitForCallback).ConfigureAwait(false);155            }156            catch (Exception ex)157            {158                if (waitForCallback && _callbacks.TryRemove(id, out _))159                {160                    callback.TaskWrapper.SetException(new MessageException(ex.Message, ex));161                }162            }163            return waitForCallback ? await callback.TaskWrapper.Task.ConfigureAwait(false) : null;164        }165        /// <summary>166        /// Detaches session from target. Once detached, session won't emit any events and can't be used to send messages.167        /// </summary>168        /// <returns></returns>169        /// <exception cref="T:PuppeteerSharp.PuppeteerException"></exception>170        public Task DetachAsync()171        {172            if (Connection == null)173            {174                throw new PuppeteerException($"Session already detached.Most likely the { TargetType } has been closed.");175            }176            return Connection.SendAsync("Target.detachFromTarget", new { sessionId = SessionId });177        }178        internal bool HasPendingCallbacks() => _callbacks.Count != 0;179        #endregion180        #region Private Methods181        internal void OnMessage(string message)182        {183            _logger.LogTrace("◀ Receive {Message}", message);184            JObject obj = null;185            try186            {187                obj = JObject.Parse(message);188            }189            catch (JsonException exc)190            {191                _logger.LogError(exc, "Failed to deserialize message", message);192                return;193            }194            var id = obj[MessageKeys.Id]?.Value<int>();195            if (id.HasValue && _callbacks.TryRemove(id.Value, out var callback))196            {197                if (obj[MessageKeys.Error] != null)198                {199                    callback.TaskWrapper.TrySetException(new MessageException(callback, obj));200                }201                else202                {203                    callback.TaskWrapper.TrySetResult(obj[MessageKeys.Result].Value<JObject>());204                }205            }206            else207            {208                var method = obj[MessageKeys.Method].AsString();209                var param = obj[MessageKeys.Params];210                if (method == "Tracing.tracingComplete")211                {212                    TracingComplete?.Invoke(this, new TracingCompleteEventArgs213                    {214                        Stream = param[MessageKeys.Stream].AsString()215                    });216                }217                else if (method == "Target.receivedMessageFromTarget")218                {219                    var sessionId = param[MessageKeys.SessionId].AsString();220                    if (_sessions.TryGetValue(sessionId, out var session))221                    {222                        session.OnMessage(param[MessageKeys.Message].AsString());223                    }224                }225                else if (method == "Target.detachedFromTarget")226                {...

Full Screen

Full Screen

TracingTests.cs

Source:TracingTests.cs Github

copy

Full Screen

...9using PuppeteerSharp.Tests.Attributes;10using PuppeteerSharp.Xunit;11using Xunit;12using Xunit.Abstractions;13namespace PuppeteerSharp.Tests.TracingTests14{15    [Collection(TestConstants.TestFixtureCollectionName)]16    public class TracingTests : PuppeteerPageBaseTest17    {18        private readonly string _file;19        public TracingTests(ITestOutputHelper output) : base(output)20        {21            _file = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());22        }23        public override async Task DisposeAsync()24        {25            await base.DisposeAsync();26            var attempts = 0;27            const int maxAttempts = 5;28            while (true)29            {30                try31                {32                    attempts++;33                    if (File.Exists(_file))34                    {35                        File.Delete(_file);36                    }37                    break;38                }39                catch (UnauthorizedAccessException)40                {41                    if (attempts == maxAttempts)42                    {43                        break;44                    }45                    await Task.Delay(1000);46                }47            }48        }49        [PuppeteerTest("tracing.spec.ts", "Tracing", "should output a trace")]50        [SkipBrowserFact(skipFirefox: true)]51        public async Task ShouldOutputATrace()52        {53            await Page.Tracing.StartAsync(new TracingOptions54            {55                Screenshots = true,56                Path = _file57            });58            await Page.GoToAsync(TestConstants.ServerUrl + "/grid.html");59            await Page.Tracing.StopAsync();60            Assert.True(File.Exists(_file));61        }62        [PuppeteerTest("tracing.spec.ts", "Tracing", "should run with custom categories if provided")]63        [SkipBrowserFact(skipFirefox: true)]64        public async Task ShouldRunWithCustomCategoriesProvided()65        {66            await Page.Tracing.StartAsync(new TracingOptions67            {68                Screenshots = true,69                Path = _file,70                Categories = new List<string>71                {72                    "disabled-by-default-v8.cpu_profiler.hires"73                }74            });75            await Page.Tracing.StopAsync();76            using (var file = File.OpenText(_file))77            using (var reader = new JsonTextReader(file))78            {79                var traceJson = JToken.ReadFrom(reader);80                Assert.Contains("disabled-by-default-v8.cpu_profiler.hires", traceJson["metadata"]["trace-config"].ToString());81            }82        }83        [PuppeteerTest("tracing.spec.ts", "Tracing", "should throw if tracing on two pages")]84        [SkipBrowserFact(skipFirefox: true)]85        public async Task ShouldThrowIfTracingOnTwoPages()86        {87            await Page.Tracing.StartAsync(new TracingOptions88            {89                Path = _file90            });91            var newPage = await Browser.NewPageAsync();92            await Assert.ThrowsAsync<InvalidOperationException>(async () =>93            {94                await Page.Tracing.StartAsync(new TracingOptions95                {96                    Path = _file97                });98            });99            await newPage.CloseAsync();100            await Page.Tracing.StopAsync();101        }102        [PuppeteerTest("tracing.spec.ts", "Tracing", "should return a buffer")]103        [SkipBrowserFact(skipFirefox: true)]104        public async Task ShouldReturnABuffer()105        {106            await Page.Tracing.StartAsync(new TracingOptions107            {108                Screenshots = true,109                Path = _file110            });111            await Page.GoToAsync(TestConstants.ServerUrl + "/grid.html");112            var trace = await Page.Tracing.StopAsync();113            var buf = File.ReadAllText(_file);114            Assert.Equal(trace, buf);115        }116        [PuppeteerTest("tracing.spec.ts", "Tracing", "should work without options")]117        [SkipBrowserFact(skipFirefox: true)]118        public async Task ShouldWorkWithoutOptions()119        {120            await Page.Tracing.StartAsync();121            await Page.GoToAsync(TestConstants.ServerUrl + "/grid.html");122            var trace = await Page.Tracing.StopAsync();123            Assert.NotNull(trace);124        }125        [PuppeteerTest("tracing.spec.ts", "Tracing", "should support a buffer without a path")]126        [SkipBrowserFact(skipFirefox: true)]127        public async Task ShouldSupportABufferWithoutAPath()128        {129            await Page.Tracing.StartAsync(new TracingOptions130            {131                Screenshots = true132            });133            await Page.GoToAsync(TestConstants.ServerUrl + "/grid.html");134            var trace = await Page.Tracing.StopAsync();135            Assert.Contains("screenshot", trace);136        }137    }138}...

Full Screen

Full Screen

Tracing.cs

Source:Tracing.cs Github

copy

Full Screen

...5using PuppeteerSharp.Messaging;6namespace PuppeteerSharp7{8    /// <summary>9    /// You can use <see cref="Tracing.StartAsync(TracingOptions)"/> and <see cref="Tracing.StopAsync"/> to create a trace file which can be opened in Chrome DevTools or timeline viewer.10    /// </summary>11    /// <example>12    /// <code>13    /// await Page.Tracing.StartAsync(new TracingOptions14    /// {15    ///     Screenshots = true,16    ///     Path = _file17    /// });18    /// await Page.GoToAsync(TestConstants.ServerUrl + "/grid.html");19    /// await Page.Tracing.StopAsync();20    /// </code>21    /// </example>22    public class Tracing23    {24        private readonly CDPSession _client;25        private bool _recording;26        private string _path;27        private static readonly List<string> _defaultCategories = new List<string>()28        {29            "-*",30            "devtools.timeline",31            "v8.execute",32            "disabled-by-default-devtools.timeline",33            "disabled-by-default-devtools.timeline.frame",34            "toplevel",35            "blink.console",36            "blink.user_timing",37            "latencyInfo",38            "disabled-by-default-devtools.timeline.stack",39            "disabled-by-default-v8.cpu_profiler"40        };41        internal Tracing(CDPSession client)42        {43            _client = client;44        }45        /// <summary>46        /// Starts tracing.47        /// </summary>48        /// <returns>Start task</returns>49        /// <param name="options">Tracing options</param>50        public async Task StartAsync(TracingOptions options)51        {52            if (_recording)53            {54                throw new InvalidOperationException("Cannot start recording trace while already recording trace.");55            }5657            if (string.IsNullOrEmpty(options.Path))58            {59                throw new ArgumentException("Must specify a path to write trace file to.");60            }616263            var categories = options.Categories ?? _defaultCategories;6465            if (options.Screenshots)66            {67                categories.Add("disabled-by-default-devtools.screenshot");68            }6970            _path = options.Path;71            _recording = true;7273            await _client.SendAsync("Tracing.start", new74            {75                transferMode = "ReturnAsStream",76                categories = string.Join(", ", categories)77            });78        }7980        /// <summary>81        /// Stops tracing82        /// </summary>83        /// <returns>Stop task</returns>84        public async Task StopAsync()85        {86            var taskWrapper = new TaskCompletionSource<bool>();8788            async void EventHandler(object sender, TracingCompleteEventArgs e)89            {90                await ReadStream(e.Stream, _path);91                _client.TracingComplete -= EventHandler;92                taskWrapper.SetResult(true);93            }9495            _client.TracingComplete += EventHandler;9697            await _client.SendAsync("Tracing.end");9899            _recording = false;100101            await taskWrapper.Task;102        }103        private async Task ReadStream(string stream, string path)104        {105            using (var fs = new StreamWriter(path))106            {107                bool eof = false;108109                while (!eof)110                {111                    var response = await _client.SendAsync<IOReadResponse>("IO.read", new...

Full Screen

Full Screen

WontImplementTests.cs

Source:WontImplementTests.cs Github

copy

Full Screen

...21        [PuppeteerTest("navigation.spec.ts", "should not leak listeners during navigation of 11 pages")]22        [PuppeteerTest("navigation.spec.ts", "should throw if networkidle is passed as an option")]23        [PuppeteerTest("launcher.spec.ts", "Puppeteer.launch", "should report the correct product")] //We don't use the product in this way24        [PuppeteerTest("launcher.spec.ts", "Puppeteer.launch", "falls back to launching chrome if there is an unknown product but logs a warning")]25        [PuppeteerTest("tracing.spec.ts", "Tracing", "should return null in case of Buffer error")]26        [PuppeteerTest("tracing.spec.ts", "Tracing", "should properly fail if readProtocolStream errors out")]27        [PuppeteerTest("fixtures.spec.ts", "Fixtures", "dumpio option should work with pipe option")]28        [PuppeteerTest("EventEmitter.spec.ts", "once", "only calls the listener once and then removes it")]29        [PuppeteerTest("EventEmitter.spec.ts", "once", "supports chaining")]30        [PuppeteerTest("EventEmitter.spec.ts", "emit", "calls all the listeners for an event")]31        [PuppeteerTest("EventEmitter.spec.ts", "emit", "passes data through to the listener")]32        [PuppeteerTest("EventEmitter.spec.ts", "emit", "returns true if the event has listeners")]33        [PuppeteerTest("EventEmitter.spec.ts", "emit", "returns false if the event has listeners")]34        [PuppeteerTest("EventEmitter.spec.ts", "listenerCount", "returns the number of listeners for the given event")]35        [PuppeteerTest("EventEmitter.spec.ts", "removeAllListeners", "removes every listener from all events by default")]36        [PuppeteerTest("EventEmitter.spec.ts", "removeAllListeners", "returns the emitter for chaining")]37        [PuppeteerTest("EventEmitter.spec.ts", "removeAllListeners", "can filter to remove only listeners for a given event name")]38        [PuppeteerTest("emulation.spec.ts", "Page.emulateMediaType", "should throw in case of bad argument")]39        [PuppeteerTest("emulation.spec.ts", "Page.emulateMediaFeatures", "should throw in case of bad argument")]40        [PuppeteerTest("emulation.spec.ts", "Page.emulateVisionDeficiency", "should throw for invalid vision deficiencies")]...

Full Screen

Full Screen

TracingOptions.cs

Source:TracingOptions.cs Github

copy

Full Screen

1using System.Collections.Generic;2namespace PuppeteerSharp3{4    /// <summary>5    /// Tracing options used on <see cref="Tracing.StartAsync(TracingOptions)"/>.6    /// </summary>7    public class TracingOptions8    {9        /// <summary>10        /// Gets or sets a value indicating whether Tracing should captures screenshots in the trace11        /// </summary>12        /// <value>Screenshots option</value>13        public bool Screenshots { get; set; }14        /// <summary>15        /// A path to write the trace file to16        /// </summary>17        /// <value>The path.</value>18        public string Path { get; set; }19        /// <summary>20        /// Specify custom categories to use instead of default.21        /// </summary>22        /// <value>The categories.</value>23        public List<string> Categories { get; set; }24    }...

Full Screen

Full Screen

TracingCompleteEventArgs.cs

Source:TracingCompleteEventArgs.cs Github

copy

Full Screen

2using System.IO;3namespace PuppeteerSharp4{5    /// <summary>6    /// <see cref="CDPSession.TracingComplete"/> arguments.7    /// </summary>8    public class TracingCompleteEventArgs : EventArgs9    {10        /// <summary>11        /// Gets or sets the stream.12        /// </summary>13        /// <value>The stream.</value>14        public string Stream { get; internal set; }15    }...

Full Screen

Full Screen

TracingStartRequest.cs

Source:TracingStartRequest.cs Github

copy

Full Screen

1namespace PuppeteerSharp.Messaging2{3    internal class TracingStartRequest4    {5        public string Categories { get; set; }6        public string TransferMode { get; set; }7    }8}...

Full Screen

Full Screen

TracingCompleteResponse.cs

Source:TracingCompleteResponse.cs Github

copy

Full Screen

1namespace PuppeteerSharp.Messaging2{3    internal class TracingCompleteResponse4    {5        public string Stream { get; set; }6    }7}...

Full Screen

Full Screen

Tracing

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().GetAwaiter().GetResult();9        }10        static async Task MainAsync()11        {12            var browser = await Puppeteer.LaunchAsync(new LaunchOptions13            {14                Args = new string[] { "--no-sandbox" }15            });16            var page = await browser.NewPageAsync();17            page.Console += (sender, e) => Console.WriteLine(e.Message.Text);18            await page.ScreenshotAsync("google.png");19            await browser.CloseAsync();20        }21    }22}23using System;24using System.Threading.Tasks;25using PuppeteerSharp;26{27    {28        static void Main(string[] args)29        {30            MainAsync().GetAwaiter().GetResult();31        }32        static async Task MainAsync()33        {34            var browser = await Puppeteer.LaunchAsync(new LaunchOptions35            {36                Args = new string[] { "--no-sandbox" }37            });38            var page = await browser.NewPageAsync();39            await page.ScreenshotAsync("google.png");40            await page.Tracing.StartAsync(new TracingOptions41            {42            });43            await page.ScreenshotAsync("bing.png");44            await page.Tracing.StopAsync();45            await browser.CloseAsync();46        }47    }48}49using System;50using System.Threading.Tasks;51using PuppeteerSharp;52{53    {54        static void Main(string[] args)55        {56            MainAsync().GetAwaiter().GetResult();57        }58        static async Task MainAsync()59        {60            var browser = await Puppeteer.LaunchAsync(new LaunchOptions61            {62                Args = new string[] { "--no-sandbox" }63            });64            var page = await browser.NewPageAsync();

Full Screen

Full Screen

Tracing

Using AI Code Generation

copy

Full Screen

1using PuppeteerSharp;2using System;3using System.Threading.Tasks;4{5    {6        static async Task Main(string[] args)7        {8            {9                Args = new string[] { "--enable-automation" },10            };11            using (var browser = await Puppeteer.LaunchAsync(options))12            {13                var page = await browser.NewPageAsync();14                await page.ScreenshotAsync("google.png");15            }16        }17    }18}19using PuppeteerSharp;20using System;21using System.Threading.Tasks;22{23    {24        static async Task Main(string[] args)25        {26            {27                Args = new string[] { "--enable-automation" },28            };29            using (var browser = await Puppeteer.LaunchAsync(options))30            {31                var page = await browser.NewPageAsync();32                await page.SetViewportAsync(new ViewPortOptions33                {34                });35                await page.ScreenshotAsync("google.png");36            }37        }38    }39}40using PuppeteerSharp;41using System;42using System.Threading.Tasks;43{44    {45        static async Task Main(string[] args)46        {47            {48                Args = new string[] { "--enable-automation" },49            };50            using (var browser = await Puppeteer.LaunchAsync(options))51            {52                var page = await browser.NewPageAsync();53                await page.SetViewportAsync(new ViewPortOptions54                {55                });56                await page.ScreenshotAsync("google.png");57                await page.SetViewportAsync(new ViewPortOptions58                {

Full Screen

Full Screen

Tracing

Using AI Code Generation

copy

Full Screen

1using PuppeteerSharp;2using System;3using System.IO;4using System.Threading.Tasks;5{6    {7        static async Task Main(string[] args)8        {9            var options = new LaunchOptions { Headless = true, SlowMo = 0 };10            options.Args = new[] { "--disable-web-security", "--disable-features=IsolateOrigins,site-per-process", "--no-sandbox" };11            options.DefaultViewport = null;12            options.IgnoreHTTPSErrors = true;13            options.IgnoreDefaultArgs = new[] { "--enable-automation" };14            options.DumpIO = true;15            options.Env = new[] { "PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=1" };16            options.ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe";17            options.HandleSIGINT = false;18            options.HandleSIGTERM = false;19            options.HandleSIGHUP = false;20            options.Timeout = 30000;21            options.UserDataDir = @"C:\Users\Public\Documents\PuppeteerSharp";22            options.Devtools = false;23            options.SlowMo = 0;24            options.Args = new[] { "--disable-web-security", "--disable-features=IsolateOrigins,site-per-process", "--no-sandbox" };25            var browser = await Puppeteer.LaunchAsync(options);26            var page = await browser.NewPageAsync();27            page.SetRequestInterceptionAsync(true);28            page.Request += async (sender, e) =>29            {30                await e.Request.ContinueAsync();31            };32            page.Response += async (sender, e) =>33            {34                Console.WriteLine($"Response: {e.Response.Url}");35            };36            await page.WaitForTimeoutAsync(3000);37            await page.CloseAsync();38            await browser.CloseAsync();39        }40    }41}

Full Screen

Full Screen

Tracing

Using AI Code Generation

copy

Full Screen

1using PuppeteerSharp;2using System;3using System.Threading.Tasks;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[] { "--start-maximized" },12            });13            var page = await browser.NewPageAsync();14            await page.WaitForSelectorAsync("input");15            await page.TypeAsync("input", "Hello World");16            await page.ClickAsync("input");17            var title = await page.GetTitleAsync();18            Console.WriteLine(title);19            await page.CloseAsync();20            await browser.CloseAsync();21        }22    }23}24using PuppeteerSharp;25using System;26using System.Threading.Tasks;27{28    {29        static async Task Main(string[] args)30        {31            await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);32            var browser = await Puppeteer.LaunchAsync(new LaunchOptions33            {34                Args = new string[] { "--start-maximized" },35            });36            var page = await browser.NewPageAsync();37            await page.WaitForSelectorAsync("input");38            await page.TypeAsync("input", "Hello World");39            await page.ClickAsync("input");40            var title = await page.GetTitleAsync();41            Console.WriteLine(title);42            await page.CloseAsync();43            await browser.CloseAsync();44        }45    }46}47using PuppeteerSharp;48using System;49using System.Threading.Tasks;50{51    {52        static async Task Main(string[] args)53        {54            await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);55            var browser = await Puppeteer.LaunchAsync(new LaunchOptions56            {

Full Screen

Full Screen

Tracing

Using AI Code Generation

copy

Full Screen

1using PuppeteerSharp;2using System;3using System.Threading.Tasks;4using System.IO;5{6    {7        static async Task Main(string[] args)8        {9            await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);10            var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });11            var page = await browser.NewPageAsync();12            var client = await page.Target.CreateCDPSessionAsync();13            await client.SendAsync("Tracing.start", new { categories = new[] { "-*", "devtools.timeline" } });14            var trace = await client.SendAsync("Tracing.end");15            await browser.CloseAsync();16            File.WriteAllText("trace.json", trace.ToString());17            Console.WriteLine("Trace file saved to trace.json");18        }19    }20}

Full Screen

Full Screen

Tracing

Using AI Code Generation

copy

Full Screen

1using PuppeteerSharp;2using System;3using System.Threading.Tasks;4{5    {6        static void Main(string[] args)7        {8            MainAsync().Wait();9            Console.WriteLine("Press any key to close the application");10            Console.ReadKey();11        }12        static async Task MainAsync()13        {14            {15                ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",16                Args = new string[] { "--start-maximized" },17            };18            using (var browser = await Puppeteer.LaunchAsync(options))19            using (var page = await browser.NewPageAsync())20            {21                await page.TypeAsync("input[name='q']", "puppeteer");22                await page.ClickAsync("input[name='btnK']");23                await page.WaitForNavigationAsync();24                await page.ScreenshotAsync("example.png");25            }26        }27    }28}29using PuppeteerSharp;30using System;31using System.Threading.Tasks;32{33    {34        static void Main(string[] args)35        {36            MainAsync().Wait();37            Console.WriteLine("Press any key to close the application");38            Console.ReadKey();39        }40        static async Task MainAsync()41        {42            {43                ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",44                Args = new string[] { "--start-maximized" },45            };46            using (var browser = await Puppeteer.LaunchAsync(options))47            using (var page = await browser.NewPageAsync())48            {49                await page.TypeAsync("input[name='q']", "puppeteer");50                await page.ClickAsync("input[name='btnK']");51                await page.WaitForNavigationAsync();52                await page.ScreenshotAsync("example.png");53            }54        }55    }56}

Full Screen

Full Screen

Tracing

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            {10                Args = new string[] { "--no-sandbox" }11            };12            using (var browser = await Puppeteer.LaunchAsync(options))13            {14                using (var page = await browser.NewPageAsync())15                {16                    var trace = await page.Tracing.StartAsync(new TracingOptions { Path = "trace.json" });17                    await trace.StopAsync();18                }19            }20        }21    }22}23var trace = await page.Tracing.StartAsync(new TracingOptions { Path = "trace.json" });24using System;25using System.IO;26using System.Threading.Tasks;27using PuppeteerSharp;28{29    {30        static async Task Main(string[] args)31        {32            {33                Args = new string[] { "--no-sandbox" }34            };35            using (var browser = await Puppeteer.LaunchAsync(options))36            {37                using (var page = await browser.NewPageAsync())38                {39                    var trace = await page.Tracing.StartAsync(new TracingOptions { Path = "trace.json" });40                    await page.GoToAsync("https

Full Screen

Full Screen

Tracing

Using AI Code Generation

copy

Full Screen

1using PuppeteerSharp;2using System.Threading.Tasks;3{4    {5        static async Task Main(string[] args)6        {7            using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions8            {9                Args = new[] { "--no-sandbox" },10            }))11            {12                var page = await browser.NewPageAsync();13                await page.Tracing.StartAsync(new TracingOptions14                {15                });16                await page.WaitForTimeoutAsync(10000);17                await page.Tracing.StopAsync();18            }19        }20    }21}22{23  "metadata": {24    "userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/77.0.3825.0 Safari/537.36",25  },26    {

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.

Run Puppeteer-sharp automation tests on LambdaTest cloud grid

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

Most used methods in Tracing

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful