Best Puppeteer-sharp code snippet using PuppeteerSharp.Connection.Connection
CDPSession.cs
Source:CDPSession.cs
...36 /// playbackRate = Convert.ToInt32(response.playbackRate / 2)37 /// });38 /// ]]></code>39 /// </summary>40 public class CDPSession : IConnection41 {42 internal CDPSession(IConnection connection, TargetType targetType, string sessionId, ILoggerFactory loggerFactory = null)43 {44 LoggerFactory = loggerFactory ?? new LoggerFactory();45 Connection = connection;46 TargetType = targetType;47 SessionId = sessionId;48 _callbacks = new ConcurrentDictionary<int, MessageTask>();49 _logger = Connection.LoggerFactory.CreateLogger<CDPSession>();50 _sessions = new ConcurrentDictionary<string, CDPSession>();51 }52 #region Private Members53 private int _lastId;54 private readonly ConcurrentDictionary<int, MessageTask> _callbacks;55 private readonly ILogger _logger;56 private readonly ConcurrentDictionary<string, CDPSession> _sessions;57 #endregion58 #region Properties59 /// <summary>60 /// Gets the target type.61 /// </summary>62 /// <value>The target type.</value>63 public TargetType TargetType { get; }64 /// <summary>65 /// Gets the session identifier.66 /// </summary>67 /// <value>The session identifier.</value>68 public string SessionId { get; }69 /// <summary>70 /// Gets the connection.71 /// </summary>72 /// <value>The connection.</value>73 internal IConnection Connection { get; private set; }74 /// <summary>75 /// Occurs when message received from Chromium.76 /// </summary>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 {227 var sessionId = param[MessageKeys.SessionId].AsString();228 if (_sessions.TryRemove(sessionId, out var session))229 {230 session.OnClosed();231 }232 }233 MessageReceived?.Invoke(this, new MessageEventArgs234 {235 MessageID = method,236 MessageData = param237 });238 }239 }240 internal void OnClosed()241 {242 if (IsClosed)243 {244 return;245 }246 IsClosed = true;247 foreach (var session in _sessions.Values.ToArray())248 {249 session.OnClosed();250 }251 _sessions.Clear();252 foreach (var callback in _callbacks.Values.ToArray())253 {254 callback.TaskWrapper.TrySetException(new TargetClosedException(255 $"Protocol error({callback.Method}): Target closed."256 ));257 }258 _callbacks.Clear();259 Closed?.Invoke(this, EventArgs.Empty);260 Connection = null;261 }262 internal CDPSession CreateSession(TargetType targetType, string sessionId)263 {264 var session = new CDPSession(this, targetType, sessionId);265 _sessions[sessionId] = session;266 return session;267 }268 #endregion269 #region IConnection270 ILoggerFactory IConnection.LoggerFactory => LoggerFactory;271 bool IConnection.IsClosed => IsClosed;272 Task<JObject> IConnection.SendAsync(string method, dynamic args, bool waitForCallback)273 => SendAsync(method, args, waitForCallback);274 IConnection IConnection.Connection => Connection;275 #endregion276 }277}...
Connection.cs
Source:Connection.cs
...16{17 /// <summary>18 /// A connection handles the communication with a Chromium browser19 /// </summary>20 public class Connection : IDisposable, IConnection21 {22 private readonly ILogger _logger;23 internal Connection(string url, int delay, IConnectionTransport transport, ILoggerFactory loggerFactory = null)24 {25 LoggerFactory = loggerFactory ?? new LoggerFactory();26 Url = url;27 Delay = delay;28 Transport = transport;29 _logger = LoggerFactory.CreateLogger<Connection>();30 Transport.MessageReceived += Transport_MessageReceived;31 Transport.Closed += Transport_Closed;32 _callbacks = new ConcurrentDictionary<int, MessageTask>();33 _sessions = new ConcurrentDictionary<string, CDPSession>();34 }35 #region Private Members36 private int _lastId;37 private readonly ConcurrentDictionary<int, MessageTask> _callbacks;38 private readonly ConcurrentDictionary<string, CDPSession> _sessions;39 #endregion40 #region Properties41 /// <summary>42 /// Gets the WebSocket URL.43 /// </summary>44 /// <value>The URL.</value>45 public string Url { get; }46 /// <summary>47 /// Gets the sleep time when a message is received.48 /// </summary>49 /// <value>The delay.</value>50 public int Delay { get; }51 /// <summary>52 /// Gets the Connection transport.53 /// </summary>54 /// <value>Connection transport.</value>55 public IConnectionTransport Transport { get; }56 /// <summary>57 /// Occurs when the connection is closed.58 /// </summary>59 public event EventHandler Closed;60 /// <summary>61 /// Occurs when a message from chromium is received.62 /// </summary>63 public event EventHandler<MessageEventArgs> MessageReceived;64 /// <summary>65 /// Gets or sets a value indicating whether this <see cref="Connection"/> is closed.66 /// </summary>67 /// <value><c>true</c> if is closed; otherwise, <c>false</c>.</value>68 public bool IsClosed { get; internal set; }69 /// <summary>70 /// Gets the logger factory.71 /// </summary>72 /// <value>The logger factory.</value>73 public ILoggerFactory LoggerFactory { get; }74 #endregion75 #region Public Methods76 internal async Task<JObject> SendAsync(string method, dynamic args = null, bool waitForCallback = true)77 {78 if (IsClosed)79 {80 throw new TargetClosedException($"Protocol error({method}): Target closed.");81 }82 var id = Interlocked.Increment(ref _lastId);83 var message = JsonConvert.SerializeObject(new Dictionary<string, object>84 {85 { MessageKeys.Id, id },86 { MessageKeys.Method, method },87 { MessageKeys.Params, args }88 });89 _logger.LogTrace("Send ⺠{Id} Method {Method} Params {@Params}", id, method, (object)args);90 MessageTask callback = null;91 if (waitForCallback)92 {93 callback = new MessageTask94 {95 TaskWrapper = new TaskCompletionSource<JObject>(),96 Method = method97 };98 _callbacks[id] = callback;99 }100 await Transport.SendAsync(message).ConfigureAwait(false);101 return waitForCallback ? await callback.TaskWrapper.Task.ConfigureAwait(false) : null;102 }103 internal async Task<T> SendAsync<T>(string method, dynamic args = null)104 {105 JToken response = await SendAsync(method, args).ConfigureAwait(false);106 return response.ToObject<T>();107 }108 internal async Task<CDPSession> CreateSessionAsync(TargetInfo targetInfo)109 {110 var sessionId = (await SendAsync("Target.attachToTarget", new111 {112 targetId = targetInfo.TargetId113 }).ConfigureAwait(false))[MessageKeys.SessionId].AsString();114 var session = new CDPSession(this, targetInfo.Type, sessionId);115 _sessions.TryAdd(sessionId, session);116 return session;117 }118 internal bool HasPendingCallbacks() => _callbacks.Count != 0;119 #endregion120 private void OnClose()121 {122 if (IsClosed)123 {124 return;125 }126 IsClosed = true;127 Transport.StopReading();128 Closed?.Invoke(this, new EventArgs());129 foreach (var session in _sessions.Values.ToArray())130 {131 session.OnClosed();132 }133 _sessions.Clear();134 foreach (var response in _callbacks.Values.ToArray())135 {136 response.TaskWrapper.TrySetException(new TargetClosedException(137 $"Protocol error({response.Method}): Target closed."138 ));139 }140 _callbacks.Clear();141 }142 internal static IConnection FromSession(CDPSession session)143 {144 var connection = session.Connection;145 while (connection is CDPSession)146 {147 connection = connection.Connection;148 }149 return connection;150 }151 #region Private Methods152 private async void Transport_MessageReceived(object sender, MessageReceivedEventArgs e)153 {154 var response = e.Message;155 JObject obj = null;156 if (response.Length > 0 && Delay > 0)157 {158 await Task.Delay(Delay).ConfigureAwait(false);159 }160 try161 {162 obj = JObject.Parse(response);163 }164 catch (JsonException exc)165 {166 _logger.LogError(exc, "Failed to deserialize response", response);167 return;168 }169 _logger.LogTrace("â Receive {Message}", response);170 var id = obj[MessageKeys.Id]?.Value<int>();171 if (id.HasValue)172 {173 //If we get the object we are waiting for we return if174 //if not we add this to the list, sooner or later some one will come for it 175 if (_callbacks.TryRemove(id.Value, out var callback))176 {177 if (obj[MessageKeys.Error] != null)178 {179 callback.TaskWrapper.TrySetException(new MessageException(callback, obj));180 }181 else182 {183 callback.TaskWrapper.TrySetResult(obj[MessageKeys.Result].Value<JObject>());184 }185 }186 }187 else188 {189 var method = obj[MessageKeys.Method].AsString();190 var param = obj[MessageKeys.Params];191 if (method == "Target.receivedMessageFromTarget")192 {193 var sessionId = param[MessageKeys.SessionId].AsString();194 if (_sessions.TryGetValue(sessionId, out var session))195 {196 session.OnMessage(param[MessageKeys.Message].AsString());197 }198 }199 else if (method == "Target.detachedFromTarget")200 {201 var sessionId = param[MessageKeys.SessionId].AsString();202 if (_sessions.TryRemove(sessionId, out var session) && !session.IsClosed)203 {204 session.OnClosed();205 }206 }207 else208 {209 MessageReceived?.Invoke(this, new MessageEventArgs210 {211 MessageID = method,212 MessageData = param213 });214 }215 }216 }217 void Transport_Closed(object sender, EventArgs e) => OnClose();218 #endregion219 #region Static Methods220 /// <summary>221 /// Gets default web socket factory implementation.222 /// </summary>223 public static readonly Func<Uri, IConnectionOptions, CancellationToken, Task<WebSocket>> DefaultWebSocketFactory = async (uri, options, cancellationToken) =>224 {225 var result = new ClientWebSocket();226 result.Options.KeepAliveInterval = TimeSpan.Zero;227 await result.ConnectAsync(uri, cancellationToken).ConfigureAwait(false);228 return result;229 };230 internal static async Task<Connection> Create(string url, IConnectionOptions connectionOptions, ILoggerFactory loggerFactory = null)231 {232 var transport = connectionOptions.Transport;233 if (transport == null)234 {235 var ws = await (connectionOptions.WebSocketFactory ?? DefaultWebSocketFactory)(236 new Uri(url),237 connectionOptions,238 default).ConfigureAwait(false);239 transport = new WebSocketTransport(ws, connectionOptions.EnqueueTransportMessages);240 }241 return new Connection(url, connectionOptions.SlowMo, transport, loggerFactory);242 }243 /// <summary>244 /// Releases all resource used by the <see cref="Connection"/> object.245 /// It will raise the <see cref="Closed"/> event and dispose <see cref="Transport"/>.246 /// </summary>247 /// <remarks>Call <see cref="Dispose"/> when you are finished using the <see cref="Connection"/>. The248 /// <see cref="Dispose"/> method leaves the <see cref="Connection"/> in an unusable state.249 /// After calling <see cref="Dispose"/>, you must release all references to the250 /// <see cref="Connection"/> so the garbage collector can reclaim the memory that the251 /// <see cref="Connection"/> was occupying.</remarks>252 public void Dispose()253 {254 OnClose();255 Transport.Dispose();256 }257 #endregion258 #region IConnection259 ILoggerFactory IConnection.LoggerFactory => LoggerFactory;260 bool IConnection.IsClosed => IsClosed;261 Task<JObject> IConnection.SendAsync(string method, dynamic args, bool waitForCallback)262 => SendAsync(method, args, waitForCallback);263 IConnection IConnection.Connection => null;264 #endregion265 }266}...
GeneratePdf.cs
Source:GeneratePdf.cs
...43 page.WaitForNavigationAsync(), 44 page.ClickAsync("#submit-button"));45 var stream = await page.PdfStreamAsync();46 await browser.CloseAsync();47 string storageConnectionString = Environment.GetEnvironmentVariable("AzureWebJobsStorage");48 BlobContainerClient container = new BlobContainerClient(storageConnectionString, "invoices");49 container.CreateIfNotExists(Azure.Storage.Blobs.Models.PublicAccessType.None);50 var blockBlobClient = container.GetBlobClient(orderId.ToString() + ".pdf");51 blockBlobClient.Upload(stream, new BlobHttpHeaders { ContentType = "application/pdf" });52 53 string sasUri = blockBlobClient.GenerateSasUri(permissions: Azure.Storage.Sas.BlobSasPermissions.Read, expiresOn: DateTime.Now.AddYears(1)).AbsoluteUri;54 var sqlConnectionString = Environment.GetEnvironmentVariable("DefaultConnection");55 using (var connection = new SqlConnection(sqlConnectionString))56 {57 string sql = "Update Orders Set Processed = -1, InvoiceURL = @InvoiceURL where OrderId = @OrderId";58 var affectedRows = connection.Execute(sql,new {OrderId = orderId, InvoiceURL = sasUri});59 }60 }61 private string GetOrderDetailsData(int orderId)62 {63 var sqlConnectionString = Environment.GetEnvironmentVariable("DefaultConnection");64 string sqlOrderDetails = "select OrderDetails.ProductId, Products.Title as [Name], Products.Price as [UnitPrice], OrderDetails.Quantity from OrderDetails INNER JOIN Products ON OrderDetails.ProductId = Products.ProductId where OrderDetails.OrderId = @OrderID";65 66 using (var connection = new SqlConnection(sqlConnectionString))67 {68 var orderDetails = connection.Query<OrderDetail>(sqlOrderDetails, new {OrderID = orderId}).ToList();69 var data = orderDetails.Select(_ => new {70 productId = _.ProductId.ToString(),71 name = _.Name,72 quantity = _.Quantity,73 unitPrice = Decimal.Parse(_.UnitPrice)74 });75 return JsonConvert.SerializeObject(data);76 }77 }78 private string GetOrderData(int orderId)79 {80 var sqlConnectionString = Environment.GetEnvironmentVariable("DefaultConnection");81 string sqlOrderDetails = "select * from [Orders] where OrderId = @OrderID";82 83 using (var connection = new SqlConnection(sqlConnectionString))84 {85 var orderDetails = connection.QueryFirstOrDefault<Order>(sqlOrderDetails, new {OrderID = orderId});86 return JsonConvert.SerializeObject(orderDetails);87 }88 }89 public class OrderDetail90 {91 public int ProductId { get; set; }92 public string Name { get; set; }93 public string UnitPrice { get; set; }94 public int Quantity { get; set; }95 }96 public class Order97 {...
Crawler.cs
Source:Crawler.cs
1using HtmlAgilityPack;2using System;3using System.Collections.Generic;4using System.Linq;5using System.Text;6using System.Text.RegularExpressions;7using System.Threading.Tasks;8namespace GoogleCrawler.Core;9public class Crawler : IDisposable10{11 public Crawler()12 {13 browserArgs.Add("sandbox", "--no-sandbox");14 }15 private readonly string _UrlRegex = @"http.*/@(?<lat>-?\d*\.\d*),(?<lon>-?\d*\.\d*),(?<zzz>\d*z).*";16 private readonly string _GoogleMapUrl = "https://google.com/maps/search";17 private string phrase;18 private string url;19 private double searchRadius;20 private string browserPath;21 private Dictionary<string, string> browserArgs = new Dictionary<string, string>();22 private PuppeteerSharp.Browser browser;23 private PuppeteerSharp.Page page;24 private bool isFirstPage = true;25 public Crawler SetPhrase(string phrase)26 {27 this.phrase = phrase.Replace(" ", "+");28 this.url = $"{_GoogleMapUrl}/{this.phrase}";29 return this;30 }31 public double SearchRadius { set => this.searchRadius = value; get => searchRadius; }32 public string BrowserPath { set => this.browserPath = value; get => browserPath; }33 private double sourceLat;34 private double sourceLon;35 private HtmlDocument doc = new HtmlDocument();36 public Crawler SetProxy(string host, int port)37 {38 if (browserArgs.ContainsKey("proxy"))39 {40 browserArgs["proxy"] = string.Concat("--proxy-server=", host, ":", port);41 }42 else43 {44 browserArgs.Add("proxy", string.Concat("--proxy-server=", host, ":", port));45 }46 return this;47 }48 public async Task Launch()49 {50 this.browser = await PuppeteerSharp.Puppeteer.LaunchAsync(new PuppeteerSharp.LaunchOptions51 {52 Headless = true,53 Timeout = 60 * 1000,54 ExecutablePath = browserPath,55 //SlowMo = 30,56 //IgnoreDefaultArgs = false,57 //IgnoredDefaultArgs = new[] { "enable-automation" },58 Args = browserArgs.Values.ToArray(),59 });60 page = (await browser.PagesAsync())[0];61 }62 public async Task Run(CancellationToken token)63 {64 65 var response = await page.GoToAsync(url);66 if (response?.Ok ?? false)67 doc.LoadHtml(await page.GetContentAsync());68 else69 {70 this.Dispose();71 Exceptions.BadOrNoResponseException badResponseException;72 if (response == null)73 badResponseException = new("There is no response from server. Please check your connection.");74 else 75 badResponseException = new(response.StatusText);76 throw badResponseException;77 }78 await ResolvePlaces(token);79 }80 private Task ResolvePlaces(CancellationToken token)81 {82 while(true && !token.IsCancellationRequested)83 {84 if (isFirstPage)85 {86 var match = Regex.Match(page.Url, _UrlRegex);87 var lat = match.Groups["lat"].Value;88 var lon = match.Groups["lon"].Value;89 if (double.TryParse(lat, out var tempLat) && double.TryParse(lon, out var tempLon))90 {91 sourceLat = tempLat;92 sourceLon = tempLon;93 }94 isFirstPage = false;95 }96 var names = doc.DocumentNode.SelectNodes("//h3[contains(@class, 'section-result-title')]");97 var results = doc.DocumentNode.SelectNodes("//*[@id='pane']/div/div[1]/div/div/div[4]/div[1]/div[contains(@class, 'section-result')]");98 for (var i = 0; i < results.Count; i++)99 {100 }101 }102 if(token.IsCancellationRequested)103 Dispose();104 return Task.CompletedTask;105 }106#pragma warning disable CA1816 // Dispose methods should call SuppressFinalize107 public void Dispose()108#pragma warning restore CA1816 // Dispose methods should call SuppressFinalize109 {110 browser.Dispose();111 }112}...
Program.cs
Source:Program.cs
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;45namespace stealthmode6{7 class Program8 {9 // Check your API key and web socket endpoint from 10 // My Products (https://browseasy.com/products/) page.1112 // Assuming that it's stored in the environment variables, 13 // e.g. wss://freemium.browseasy.com14 static readonly string BROWSEASY_ENDPOINT =15 Environment.GetEnvironmentVariable("BROWSEASY_ENDPOINT");1617 // Assuming that it's stored in the environment variables18 // e.g. ccc70169f82f4c7c8a33ecca21c1becf19 static readonly string BROWSEASY_API_KEY =20 Environment.GetEnvironmentVariable("BROWSEASY_API_KEY");2122 // Your unique connection string.23 static readonly string BROWSEASY_CONNECTION_STRING = $"{BROWSEASY_ENDPOINT}?code={BROWSEASY_API_KEY}";2425 // Your unique connection string with stealth mode enabled.26 static readonly string BROWSEASY_STEALTH_CONNECTION_STRING = $"{BROWSEASY_CONNECTION_STRING}&stealth";2728 public static async Task Main()29 {30 var options = new ConnectOptions()31 {32 BrowserWSEndpoint = BROWSEASY_STEALTH_CONNECTION_STRING,33 // Always reset default viewport.34 // When stealth mode enabled, Browseasy will launch your browser 35 // with a random resolution based on a sample distribution. 36 // See https://gs.statcounter.com/screen-resolution-stats/desktop/worldwide37 DefaultViewport = null38 };3940 // Run headless browser on the cloud.41 using (var browser = await PuppeteerSharp.Puppeteer.ConnectAsync(options))42 {43 using (var page = await browser.NewPageAsync())44 {45 await page.GoToAsync("https://fingerprintjs.github.io/fingerprintjs/");46 await page.ScreenshotAsync("fingerprintjs.png");47 }48 }49 }50 }51}
...
PuppeteerEngine.cs
Source:PuppeteerEngine.cs
...26 var dic = new Dictionary<string, string>();27 dic.Add("Referer", _settings.Bet365.Url.MainPage.ToString());28 dic.Add("Accept-Encoding", "gzip, deflate, br");29 dic.Add("Accept-Language", "zh-TW,zh;q=0.9,en-US;q=0.8,en;q=0.7,zh-CN;q=0.6");30 dic.Add("Connection", "keep-alive");31 await page.EmulateAsync(IPhone);32 await page.SetRequestInterceptionAsync(true);33 await page.SetExtraHttpHeadersAsync(dic);34 page.Request += async (sender, e) =>35 {36 if (e.Request.ResourceType == ResourceType.Image)37 await e.Request.AbortAsync();38 else39 await e.Request.ContinueAsync();40 };41 return page;42 }43 public async void launchBrowser(){44 _browser = await Puppeteer.LaunchAsync(new LaunchOptions...
PdfGenerator.cs
Source:PdfGenerator.cs
...16 _converter = converter;17 }18 public async Task<Stream> CreatePdfAsync(string html, Configuration.PdfOptions pdfOptions)19 {20 using (var browser = await Puppeteer.ConnectAsync(GetConnectionOptions()))21 using (var page = await browser.NewPageAsync())22 {23 await Task.WhenAll(page.SetContentAsync(html), 24 page.SetCacheEnabledAsync(false));25 26 return await page.PdfStreamAsync(_converter.Convert(pdfOptions));27 }28 }29 public async Task<Stream> CreatePdfFromUrlAsync(string url, Configuration.PdfOptions pdfOptions)30 {31 using (var browser = await Puppeteer.ConnectAsync(GetConnectionOptions()))32 using (var page = await browser.NewPageAsync())33 {34 await page.GoToAsync(url);35 return await page.PdfStreamAsync(_converter.Convert(pdfOptions));36 }37 }38 private ConnectOptions GetConnectionOptions()39 {40 return new ConnectOptions()41 {42 BrowserWSEndpoint = _pdfGeneratorOptions.Connection43 };44 }45 }46}...
IConnection.cs
Source:IConnection.cs
...4using Newtonsoft.Json.Linq;5namespace PuppeteerSharp6{7 /// <summary>8 /// Connection interface implemented by <see cref="Connection"/> and <see cref="CDPSession"/>9 /// </summary>10 internal interface IConnection11 {12 /// <summary>13 /// Gets the logger factory.14 /// </summary>15 /// <value>The logger factory.</value>16 ILoggerFactory LoggerFactory { get; }17 /// <summary>18 /// Gets a value indicating whether this <see cref="T:PuppeteerSharp.IConnection"/> is closed.19 /// </summary>20 /// <value><c>true</c> if is closed; otherwise, <c>false</c>.</value>21 bool IsClosed { get; }22 /// <summary>23 /// Sends a message to chromium.24 /// </summary>25 /// <returns>The async.</returns>26 /// <param name="method">Method to call.</param>27 /// <param name="args">Method arguments.</param>28 /// <param name="waitForCallback">29 /// If <c>true</c> the method will return a task to be completed when the message is confirmed by Chromium.30 /// If <c>false</c> the task will be considered complete after sending the message to Chromium.31 /// </param>32 Task<JObject> SendAsync(string method, dynamic args = null, bool waitForCallback = true);33 /// <summary>34 /// Gets the parent connection35 /// </summary>36 IConnection Connection { get; }37 /// <summary>38 /// Occurs when the connection is closed.39 /// </summary>40 event EventHandler Closed;41 }42}...
Connection
Using AI Code Generation
1using PuppeteerSharp;2using System;3using System.Threading.Tasks;4{5 {6 static async Task Main(string[] args)7 {8 var connection = await Puppeteer.ConnectAsync(new ConnectOptions9 {
Connection
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static async Task Main(string[] args)7 {8 var browser = await Puppeteer.ConnectAsync(connection);9 var page = await browser.NewPageAsync();10 await page.ScreenshotAsync("screenshot.png");11 await browser.CloseAsync();12 }13 }14}
Connection
Using AI Code Generation
1using System;2using PuppeteerSharp;3{4 static void Main(string[] args)5 {6 var browser = await Puppeteer.ConnectAsync(connection);7 var page = await browser.NewPageAsync();8 await page.ScreenshotAsync("google.png");9 await browser.CloseAsync();10 }11}12using System;13using PuppeteerSharp;14{15 static void Main(string[] args)16 {17 var browser = await Puppeteer.ConnectAsync(connection);18 var page = await browser.NewPageAsync();
Connection
Using AI Code Generation
1var client = await connection.CreateSessionAsync();2var result = await client.SendAsync("Page.navigate", new Dictionary<string, object>3{4});5await client.CloseAsync();6await connection.CloseAsync();7var fetcher = new BrowserFetcher();8await fetcher.DownloadAsync(BrowserFetcher.DefaultRevision);9var browser = await Puppeteer.LaunchAsync(new LaunchOptions10{11 ExecutablePath = fetcher.GetExecutablePath(BrowserFetcher.DefaultRevision),12});13var page = await browser.NewPageAsync();14await browser.CloseAsync();15var fetcher = new BrowserFetcher();16await fetcher.DownloadAsync(BrowserFetcher.DefaultRevision);17var browser = await Puppeteer.LaunchAsync(new LaunchOptions18{19 ExecutablePath = fetcher.GetExecutablePath(BrowserFetcher.DefaultRevision),20});21var page = await browser.NewPageAsync();22await browser.CloseAsync();23var fetcher = new BrowserFetcher();24await fetcher.DownloadAsync(BrowserFetcher.DefaultRevision);25var browser = await Puppeteer.LaunchAsync(new LaunchOptions26{27 ExecutablePath = fetcher.GetExecutablePath(BrowserFetcher.DefaultRevision),28});29var page = await browser.NewPageAsync();30await browser.CloseAsync();31var fetcher = new BrowserFetcher();32await fetcher.DownloadAsync(BrowserFetcher.DefaultRevision);33var browser = await Puppeteer.LaunchAsync(new LaunchOptions34{35 ExecutablePath = fetcher.GetExecutablePath(BrowserFetcher.DefaultRevision),36});
Connection
Using AI Code Generation
1var browser = await Puppeteer.ConnectAsync(connection);2var page = await browser.NewPageAsync();3await page.ScreenshotAsync("2.png", new ScreenshotOptions { FullPage = true });4var browserFetcher = new BrowserFetcher();5await browserFetcher.DownloadAsync();6var page = await browser.NewPageAsync();7await page.ScreenshotAsync("3.png", new ScreenshotOptions { FullPage = true });8var browserFetcher = new BrowserFetcher();9await browserFetcher.DownloadAsync();10var page = await browser.NewPageAsync();11await page.ScreenshotAsync("4.png", new ScreenshotOptions { FullPage = true });12var browserFetcher = new BrowserFetcher();13await browserFetcher.DownloadAsync();
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!