Best Puppeteer-sharp code snippet using PuppeteerSharp.RequestEventArgs
NetworkManager.cs
Source:NetworkManager.cs
...32 }33 #region Public Properties34 internal Dictionary<string, string> ExtraHTTPHeaders => _extraHTTPHeaders?.Clone();35 internal event EventHandler<ResponseCreatedEventArgs> Response;36 internal event EventHandler<RequestEventArgs> Request;37 internal event EventHandler<RequestEventArgs> RequestFinished;38 internal event EventHandler<RequestEventArgs> RequestFailed;39 internal FrameManager FrameManager { get; set; }40 #endregion41 #region Public Methods42 internal Task AuthenticateAsync(Credentials credentials)43 {44 _credentials = credentials;45 return UpdateProtocolRequestInterceptionAsync();46 }47 internal Task SetExtraHTTPHeadersAsync(Dictionary<string, string> extraHTTPHeaders)48 {49 _extraHTTPHeaders = new Dictionary<string, string>();50 foreach (var item in extraHTTPHeaders)51 {52 _extraHTTPHeaders[item.Key.ToLower()] = item.Value;53 }54 return _client.SendAsync("Network.setExtraHTTPHeaders", new Dictionary<string, object>55 {56 { MessageKeys.Headers, _extraHTTPHeaders }57 });58 }59 internal async Task SetOfflineModeAsync(bool value)60 {61 if (_offine != value)62 {63 _offine = value;64 await _client.SendAsync("Network.emulateNetworkConditions", new Dictionary<string, object>65 {66 { MessageKeys.Offline, value},67 { MessageKeys.Latency, 0},68 { MessageKeys.DownloadThroughput, -1},69 { MessageKeys.UploadThroughput, -1}70 }).ConfigureAwait(false);71 }72 }73 internal Task SetUserAgentAsync(string userAgent)74 => _client.SendAsync("Network.setUserAgentOverride", new Dictionary<string, object>75 {76 { MessageKeys.UserAgent, userAgent }77 });78 internal Task SetRequestInterceptionAsync(bool value)79 {80 _userRequestInterceptionEnabled = value;81 return UpdateProtocolRequestInterceptionAsync();82 }83 #endregion84 #region Private Methods85 private async void Client_MessageReceived(object sender, MessageEventArgs e)86 {87 switch (e.MessageID)88 {89 case "Network.requestWillBeSent":90 OnRequestWillBeSent(e.MessageData.ToObject<RequestWillBeSentPayload>());91 break;92 case "Network.requestIntercepted":93 await OnRequestInterceptedAsync(e.MessageData.ToObject<RequestInterceptedResponse>()).ConfigureAwait(false);94 break;95 case "Network.requestServedFromCache":96 OnRequestServedFromCache(e.MessageData.ToObject<RequestServedFromCacheResponse>());97 break;98 case "Network.responseReceived":99 OnResponseReceived(e.MessageData.ToObject<ResponseReceivedResponse>());100 break;101 case "Network.loadingFinished":102 OnLoadingFinished(e.MessageData.ToObject<LoadingFinishedResponse>());103 break;104 case "Network.loadingFailed":105 OnLoadingFailed(e.MessageData.ToObject<LoadingFailedResponse>());106 break;107 }108 }109 private void OnLoadingFailed(LoadingFailedResponse e)110 {111 // For certain requestIds we never receive requestWillBeSent event.112 // @see https://crbug.com/750469113 if (_requestIdToRequest.TryGetValue(e.RequestId, out var request))114 {115 request.Failure = e.ErrorText;116 request.Response?.BodyLoadedTaskWrapper.SetResult(true);117 _requestIdToRequest.Remove(request.RequestId);118 if (request.InterceptionId != null)119 {120 _attemptedAuthentications.Remove(request.InterceptionId);121 }122 RequestFailed(this, new RequestEventArgs123 {124 Request = request125 });126 }127 }128 private void OnLoadingFinished(LoadingFinishedResponse e)129 {130 // For certain requestIds we never receive requestWillBeSent event.131 // @see https://crbug.com/750469132 if (_requestIdToRequest.TryGetValue(e.RequestId, out var request))133 {134 request.Response?.BodyLoadedTaskWrapper.SetResult(true);135 _requestIdToRequest.Remove(request.RequestId);136 if (request.InterceptionId != null)137 {138 _attemptedAuthentications.Remove(request.InterceptionId);139 }140 RequestFinished?.Invoke(this, new RequestEventArgs141 {142 Request = request143 });144 }145 }146 private void OnResponseReceived(ResponseReceivedResponse e)147 {148 // FileUpload sends a response without a matching request.149 if (_requestIdToRequest.TryGetValue(e.RequestId, out var request))150 {151 var response = new Response(152 _client,153 request,154 e.Response);155 request.Response = response;156 Response?.Invoke(this, new ResponseCreatedEventArgs157 {158 Response = response159 });160 }161 }162 private async Task OnRequestInterceptedAsync(RequestInterceptedResponse e)163 {164 if (e.AuthChallenge != null)165 {166 var response = "Default";167 if (_attemptedAuthentications.Contains(e.InterceptionId))168 {169 response = "CancelAuth";170 }171 else if (_credentials != null)172 {173 response = "ProvideCredentials";174 _attemptedAuthentications.Add(e.InterceptionId);175 }176 var credentials = _credentials ?? new Credentials();177 try178 {179 await _client.SendAsync("Network.continueInterceptedRequest", new Dictionary<string, object>180 {181 { MessageKeys.InterceptionId, e.InterceptionId },182 { MessageKeys.AuthChallengeResponse, new183 {184 response,185 username = credentials.Username,186 password = credentials.Password187 }188 }189 }).ConfigureAwait(false);190 }191 catch (PuppeteerException ex)192 {193 _logger.LogError(ex.ToString());194 }195 return;196 }197 if (!_userRequestInterceptionEnabled && _protocolRequestInterceptionEnabled)198 {199 try200 {201 await _client.SendAsync("Network.continueInterceptedRequest", new Dictionary<string, object>202 {203 { MessageKeys.InterceptionId, e.InterceptionId }204 }).ConfigureAwait(false);205 }206 catch (PuppeteerException ex)207 {208 _logger.LogError(ex.ToString());209 }210 }211 var requestHash = e.Request.Hash;212 var requestId = _requestHashToRequestIds.FirstValue(requestHash);213 if (requestId != null)214 {215 _requestIdToRequestWillBeSentEvent.TryGetValue(requestId, out var requestWillBeSentEvent);216 if (requestWillBeSentEvent != null)217 {218 OnRequest(requestWillBeSentEvent, e.InterceptionId);219 _requestHashToRequestIds.Delete(requestHash, requestId);220 _requestIdToRequestWillBeSentEvent.Remove(requestId);221 }222 }223 else224 {225 _requestHashToInterceptionIds.Add(requestHash, e.InterceptionId);226 }227 }228 private void OnRequest(RequestWillBeSentPayload e, string interceptionId)229 {230 Request request;231 var redirectChain = new List<Request>();232 if (e.RedirectResponse != null)233 {234 _requestIdToRequest.TryGetValue(e.RequestId, out request);235 // If we connect late to the target, we could have missed the requestWillBeSent event.236 if (request != null)237 {238 HandleRequestRedirect(request, e.RedirectResponse);239 redirectChain = request.RedirectChainList;240 }241 }242 Frame frame = null;243 FrameManager?.Frames.TryGetValue(e.FrameId, out frame);244 request = new Request(245 _client,246 frame,247 interceptionId,248 _userRequestInterceptionEnabled,249 e,250 redirectChain);251 _requestIdToRequest.Add(e.RequestId, request);252 Request(this, new RequestEventArgs253 {254 Request = request255 });256 }257 private void OnRequestServedFromCache(RequestServedFromCacheResponse response)258 {259 if (_requestIdToRequest.TryGetValue(response.RequestId, out var request))260 {261 request.FromMemoryCache = true;262 }263 }264 private void HandleRequestRedirect(Request request, ResponsePayload responseMessage)265 {266 var response = new Response(267 _client,268 request,269 responseMessage);270 request.Response = response;271 request.RedirectChainList.Add(request);272 response.BodyLoadedTaskWrapper.TrySetException(273 new PuppeteerException("Response body is unavailable for redirect responses"));274 if (request.RequestId != null)275 {276 _requestIdToRequest.Remove(request.RequestId);277 }278 if (request.InterceptionId != null)279 {280 _attemptedAuthentications.Remove(request.InterceptionId);281 }282 Response(this, new ResponseCreatedEventArgs283 {284 Response = response285 });286 RequestFinished(this, new RequestEventArgs287 {288 Request = request289 });290 }291 private void OnRequestWillBeSent(RequestWillBeSentPayload e)292 {293 if (_protocolRequestInterceptionEnabled)294 {295 var requestHash = e.Request.Hash;296 var interceptionId = _requestHashToInterceptionIds.FirstValue(requestHash);297 if (interceptionId != null)298 {299 OnRequest(e, interceptionId);300 _requestHashToInterceptionIds.Delete(requestHash, interceptionId);...
Program.cs
Source:Program.cs
...110 private static void Page_Response(object sender, ResponseCreatedEventArgs e)111 {112 Console.WriteLine(e.Response.Status);113 }114 private static void Page_Request(object sender, RequestEventArgs e)115 {116 Console.WriteLine(e.Request.ResourceType.ToString());117 Console.WriteLine(e.Request.Url);118 }119 private static async Task TypeFieldValue(Page page, string fieldSelector, string value, int delay = 0)120 {121 await page.FocusAsync(fieldSelector);122 await page.TypeAsync(fieldSelector, value, new TypeOptions { Delay = delay });123 await page.Keyboard.PressAsync("Tab");124 }125 private static async Task TypeFieldValueSearch(Page page, string fieldSelector, string value, int delay = 0)126 {127 await page.FocusAsync(fieldSelector);128 await page.TypeAsync(fieldSelector, value, new TypeOptions { Delay = delay });...
CaptureNetwork.cs
Source:CaptureNetwork.cs
...12 private readonly Page _Page;13 public CaptureNetwork(Page page)14 {15 _Page = page;16 _Page.Request += new EventHandler<RequestEventArgs>(onRequest);17 _Page.Response += new EventHandler<ResponseCreatedEventArgs>(onResponse);18 MapFilterRequest = new Dictionary<string, RequestFilters.RequestFilterBase>();19 MapFilterResponse = new Dictionary<string, RequestFilters.RequestFilterBase>();20 }21 public IDictionary<string, RequestFilters.RequestFilterBase> MapFilterRequest { get; set; }22 public IDictionary<string, RequestFilters.RequestFilterBase> MapFilterResponse { get; set; }23 public void AddFilter(RequestFilterBase filter)24 {25 if (filter.IsCaptureReponse)26 {27 MapFilterResponse.Add(filter.Key.ToLower(), filter);28 }29 if (filter.IsCaptureRequest)30 {31 MapFilterRequest.Add(filter.Key.ToLower(), filter);32 }33 }34 private void onResponse(object sender, ResponseCreatedEventArgs e)35 {36 var url = new Uri(e.Response.Url);37 if (MapFilterResponse.ContainsKey(url.AbsolutePath.ToLower()))38 {39 var filter = MapFilterResponse[url.AbsolutePath.ToLower()];40 _ = filter.OnResponse?.Invoke(filter, e);41 }42 Console.WriteLine(url.AbsolutePath);43 }44 private void onRequest(object sender, RequestEventArgs e)45 {46 var url = new Uri(e.Request.Url);47 if (MapFilterRequest.ContainsKey(url.AbsolutePath.ToLower()))48 {49 var filter = MapFilterRequest[url.AbsolutePath.ToLower()];50 _ = filter.OnRequest?.Invoke(filter, e);51 }52 Console.WriteLine(url.AbsolutePath);53 }54 }55}
BlockResourcesPlugin.cs
Source:BlockResourcesPlugin.cs
...30 {31 await page.SetRequestInterceptionAsync(true);32 page.Request += (sender, args) => OnPageRequest(page, args);33 }34 private async void OnPageRequest(Page sender, RequestEventArgs e)35 {36 if (BlockResources.Any(rule => rule.IsRequestBlocked(sender, e.Request)))37 {38 await e.Request.AbortAsync();39 return;40 }41 await e.Request.ContinueAsync();42 }43 public override void BeforeLaunch(LaunchOptions options)44 {45 options.Args = options.Args.Append("--site-per-process").Append("--disable-features=IsolateOrigins").ToArray();46 }47 }48}...
RequestFilterMyDragonPage.cs
Source:RequestFilterMyDragonPage.cs
...9{10 public class RequestFilterMyDragonPage : RequestFilterBase11 {12 public delegate void OnResponseMyPageDragon(ResponseCreatedEventArgs e, MyPageDragonDTO myPageDragonDTO);13 public delegate void OnProcessRequestMyPageDragon(RequestFilterBase a1, RequestEventArgs a2);14 public event OnResponseMyPageDragon OnResponseListener;15 public event OnProcessRequestMyPageDragon OnRequestListener;16 public RequestFilterMyDragonPage()17 {18 var url = new Uri("https://devabcde-api.dragonwars.game/v1/dragons/my-dragon");19 Key = url.AbsolutePath.ToLower();20 IsCaptureReponse = true;21 IsCaptureRequest = true;22 OnResponse = ProcessResponse;23 OnRequest = ProcessRequest;24 }25 private Task ProcessRequest(RequestFilterBase arg1, RequestEventArgs arg2)26 {27 OnRequestListener?.Invoke(arg1, arg2);28 return Task.CompletedTask;29 }30 private async Task ProcessResponse(RequestFilterBase arg1, ResponseCreatedEventArgs arg2)31 {32 if (arg2.Response.Status == System.Net.HttpStatusCode.OK)33 {34 var res = await arg2.Response.JsonAsync<MyPageDragonDTO>();35 OnResponseListener?.Invoke(arg2, res);36 }37 }38 }39}...
UIActionBase.cs
Source:UIActionBase.cs
...13 internal static readonly System.Text.RegularExpressions.Regex RegexBlockMeta = new System.Text.RegularExpressions.Regex("/gurux/$");14 public Microsoft.Azure.WebJobs.Host.TraceWriter log;15 public int DefaultTimeout = 7000;16 public abstract Task<T> RunAsync(Page page);17 public async void DenyRequests(object sender, RequestEventArgs e)18 {19 if (log != null)20 {21 this.log.Warning(e.Request.Url);22 }23 if (!RequestConsumer.IsRunning)24 {25 RequestConsumer.Start();26 }27 RequestConsumer.AddRequest(e.Request);28 }29 }30}...
RequestFilterBase.cs
Source:RequestFilterBase.cs
...7{8 public class RequestFilterBase9 {10 public string Key { get; set; }11 public Func<RequestFilterBase, RequestEventArgs, Task> OnRequest { get; set; }12 public Func<RequestFilterBase, ResponseCreatedEventArgs,Task> OnResponse { get; set; }13 public bool IsCaptureRequest { get; set; }14 public bool IsCaptureReponse { get; set; }15 }16}...
RequestEventArgs.cs
Source:RequestEventArgs.cs
...6 /// </summary>7 /// <seealso cref="Page.Request"/>8 /// <seealso cref="Page.RequestFailed"/>9 /// <seealso cref="Page.RequestFinished"/>10 public class RequestEventArgs : EventArgs11 {12 /// <summary>13 /// Gets or sets the request.14 /// </summary>15 /// <value>The request.</value>16 public Request Request { get; internal set; }17 }18}...
RequestEventArgs
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.LaunchAsync(new LaunchOptions { Headless = false });9 var page = await browser.NewPageAsync();10 await page.WaitForSelectorAsync("input[name=q]");11 await page.TypeAsync("input[name=q]", "PuppeteerSharp");12 await page.ClickAsync("input[name=btnK]");13 await page.WaitForNavigationAsync();14 var title = await page.GetTitleAsync();15 Console.WriteLine(title);16 await browser.CloseAsync();17 }18 }19}
RequestEventArgs
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static void Main(string[] args) => MainAsync().GetAwaiter().GetResult();7 static async Task MainAsync()8 {9 var browser = await Puppeteer.LaunchAsync(new LaunchOptions10 {11 });12 var page = await browser.NewPageAsync();13 await page.ScreenshotAsync("google.png");14 await browser.CloseAsync();15 }16 }17}18using System;19using System.Threading.Tasks;20using PuppeteerSharp;21{22 {23 static void Main(string[] args) => MainAsync().GetAwaiter().GetResult();24 static async Task MainAsync()25 {26 var browser = await Puppeteer.LaunchAsync(new LaunchOptions27 {28 });29 var page = await browser.NewPageAsync();30 await page.ScreenshotAsync("google.png");31 await browser.CloseAsync();32 }33 }34}35using System;36using System.Threading.Tasks;37using PuppeteerSharp;38{39 {40 static void Main(string[] args) => MainAsync().GetAwaiter().GetResult();41 static async Task MainAsync()42 {43 var browser = await Puppeteer.LaunchAsync(new LaunchOptions44 {45 });46 var page = await browser.NewPageAsync();47 await page.ScreenshotAsync("google.png");48 await browser.CloseAsync();49 }50 }51}52using System;53using System.Threading.Tasks;54using PuppeteerSharp;55{56 {57 static void Main(string[] args) => MainAsync().GetAwaiter().GetResult();
RequestEventArgs
Using AI Code Generation
1using PuppeteerSharp;2using System;3using System.Threading.Tasks;4{5 {6 static async Task Main(string[] args)7 {8 var browser = await Puppeteer.LaunchAsync(new LaunchOptions9 {10 });11 var page = await browser.NewPageAsync();12 page.RequestCreated += Page_RequestCreated;13 await page.WaitForSelectorAsync("input[name=q]");14 await page.TypeAsync("input[name=q]", "PuppeteerSharp");15 await page.PressAsync("input[name=q]", "Enter");16 await page.WaitForNavigationAsync();17 await page.ScreenshotAsync("google.png");18 await browser.CloseAsync();19 }20 private static void Page_RequestCreated(object sender, RequestEventArgs e)21 {22 Console.WriteLine(e.Request.Url);23 }24 }25}
RequestEventArgs
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static void Main(string[] args)7 {8 MainAsync(args).Wait();9 }10 static async Task MainAsync(string[] args)11 {12 using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false }))13 using (var page = await browser.NewPageAsync())14 {15 await page.ScreenshotAsync("google.png");16 await page.EvaluateFunctionAsync("() => alert('Hello World!')");17 await page.WaitForSelectorAsync("text=Hello World!");18 }19 }20 }21}22using System;23using System.Threading.Tasks;24using PuppeteerSharp;25{26 {27 static void Main(string[] args)28 {29 MainAsync(args).Wait();30 }31 static async Task MainAsync(string[] args)32 {33 using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false }))34 using (var page = await browser.NewPageAsync())35 {36 await page.ScreenshotAsync("google.png");37 await page.EvaluateFunctionAsync("() => alert('Hello World!')");38 await page.WaitForSelectorAsync("text=Hello World!");39 }40 }41 }42}43using System;44using System.Threading.Tasks;45using PuppeteerSharp;46{47 {48 static void Main(string[] args)49 {50 MainAsync(args).Wait();51 }52 static async Task MainAsync(string[] args)53 {54 using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false }))55 using (var page = await browser.NewPageAsync())56 {57 await page.ScreenshotAsync("google.png");58 await page.EvaluateFunctionAsync("() => alert('Hello World!')");59 await page.WaitForSelectorAsync("text=Hello World!");60 }61 }62 }63}
RequestEventArgs
Using AI Code Generation
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 });12 var page = await browser.NewPageAsync();13 page.Request += async (sender, e) =>14 {15 Console.WriteLine(e.Request.ResourceType);16 Console.WriteLine(e.Request.Url);17 };
RequestEventArgs
Using AI Code Generation
1var browser = await Puppeteer.LaunchAsync(new LaunchOptions2{3});4var page = await browser.NewPageAsync();5await page.ScreenshotAsync("google.png");6await browser.CloseAsync();7var browser = await Puppeteer.LaunchAsync(new LaunchOptions8{9});10var page = await browser.NewPageAsync();11await page.ScreenshotAsync("google.png");12await browser.CloseAsync();13var browser = await Puppeteer.LaunchAsync(new LaunchOptions14{15});16var page = await browser.NewPageAsync();17await page.ScreenshotAsync("google.png");18await browser.CloseAsync();19var browser = await Puppeteer.LaunchAsync(new LaunchOptions20{21});22var page = await browser.NewPageAsync();23await page.ScreenshotAsync("google.png");24await browser.CloseAsync();25var browser = await Puppeteer.LaunchAsync(new LaunchOptions26{27});28var page = await browser.NewPageAsync();29await page.ScreenshotAsync("google.png");30await browser.CloseAsync();31var browser = await Puppeteer.LaunchAsync(new LaunchOptions32{33});34var page = await browser.NewPageAsync();35await page.ScreenshotAsync("google.png");36await browser.CloseAsync();37var browser = await Puppeteer.LaunchAsync(new LaunchOptions38{39});40var page = await browser.NewPageAsync();
RequestEventArgs
Using AI Code Generation
1using PuppeteerSharp;2using System;3{4 {5 static void Main(string[] args)6 {7 {8 };9 using (var browser = Puppeteer.LaunchAsync(options).Result)10 {11 using (var page = browser.NewPageAsync().Result)12 {13 page.Request += Page_Request;14 page.RequestFinished += Page_RequestFinished;15 page.RequestFailed += Page_RequestFailed;16 page.RequestAborted += Page_RequestAborted;17 page.Request += Page_Request1;18 page.RequestFinished += Page_RequestFinished1;19 page.RequestFailed += Page_RequestFailed1;20 page.RequestAborted += Page_RequestAborted1;21 page.Request += Page_Request2;22 page.RequestFinished += Page_RequestFinished2;23 page.RequestFailed += Page_RequestFailed2;24 page.RequestAborted += Page_RequestAborted2;25 page.Request += Page_Request3;26 page.RequestFinished += Page_RequestFinished3;27 page.RequestFailed += Page_RequestFailed3;28 page.RequestAborted += Page_RequestAborted3;29 page.Request += Page_Request4;30 page.RequestFinished += Page_RequestFinished4;31 page.RequestFailed += Page_RequestFailed4;32 page.RequestAborted += Page_RequestAborted4;33 page.Request += Page_Request5;34 page.RequestFinished += Page_RequestFinished5;35 page.RequestFailed += Page_RequestFailed5;36 page.RequestAborted += Page_RequestAborted5;37 page.Request += Page_Request6;38 page.RequestFinished += Page_RequestFinished6;39 page.RequestFailed += Page_RequestFailed6;40 page.RequestAborted += Page_RequestAborted6;41 page.Request += Page_Request7;42 page.RequestFinished += Page_RequestFinished7;43 page.RequestFailed += Page_RequestFailed7;44 page.RequestAborted += Page_RequestAborted7;45 page.Request += Page_Request8;46 page.RequestFinished += Page_RequestFinished8;47 page.RequestFailed += Page_RequestFailed8;48 page.RequestAborted += Page_RequestAborted8;49 page.Request += Page_Request9;50 page.RequestFinished += Page_RequestFinished9;51 page.RequestFailed += Page_RequestFailed9;52 page.RequestAborted += Page_RequestAborted9;
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!!