Best Puppeteer-sharp code snippet using PuppeteerSharp.Payload
PuppeteerBrowser.cs
Source:PuppeteerBrowser.cs
...136 await MetaMaskPage.BringToFrontAsync();137 await MetaMaskPage.GoToAsync(_UrlMetaMashPopup);138 await Task.Delay(2000);139 }140 public async Task<IList<PayloadDragonPage>> GetPageInfosAsync(MyPageDragonDTO myPageDragonDTO)141 {142 var lstData = new List<PayloadDragonPage>();143 for (int i = 1; i <= myPageDragonDTO.Payload.TotalPage; i++)144 {145 var client = new RestClient($"https://devabcde-api.dragonwars.game/v1/dragons/my-dragon?page={i}&rowPerPage=12&type=DRAGON");146 var request = new RestRequest();147 request.Method = Method.Get;148 request.AddHeader("wallet", _Option.Wallet);149 var response = await client.ExecuteAsync<MyPageDragonDTO>(request);150 lstData.Add(response.Data.Payload);151 }152 return lstData;153 }154 public async Task<IList<CardInfo>> GetCardItemsAsync(int page)155 {156 await Task.Delay(2000);157 await GotoNavigatePageAsync(page);158 var lstData = new List<CardInfo>();159 var lstTemp = await RootPage.QuerySelectorAllAsync(".grid > div.relative");160 var regexSpan = new Regex(@"^\s*#\d+\s*$");161 var regexbtn = new Regex(@"^\s*Adventure\s*$", RegexOptions.IgnoreCase);162 foreach (var item in lstTemp)163 {164 var spans = await item.QuerySelectorAllAsync("span");165 var card = new CardInfo();166 foreach (var span in spans)167 {168 var content = await span.EvaluateFunctionAsync<string>("e => e.textContent", item);169 if (regexSpan.IsMatch(content))170 {171 card.Id = content;172 break;173 }174 }175 //var buttons = await item.QuerySelectorAllAsync("button");176 //foreach (var button in buttons)177 //{178 // var content = await button.EvaluateFunctionAsync<string>("e => e.textContent", item);179 // if (regexbtn.IsMatch(content))180 // {181 // await item.ClickAsync();182 // card.AdventureButton = item;183 // break;184 // }185 //}186 lstData.Add(card);187 }188 return lstData;189 }190 public IList<HashSet<string>> GetAdventureForPage(AppInfo appInfo)191 {192 return appInfo.PayloadDragonPages.Select(x =>193 {194 var temp = (from d in x.Data195 join a in appInfo.AdventureInfo.Payload196 on d.Id equals a197 select $"#{a}");198 return temp.ToHashSet();199 }).ToList();200 }201 public async Task AdventureClickAsync(int index)202 {203 await RootPage.BringToFrontAsync();204 await RootPage.ClickAsync($".grid > div.relative:nth-child({index + 1}) button:nth-child(2)");205 }206 public async Task RunAdventureClick(AppInfo appInfo)207 {208 await Task.Delay(2000);209 //var lstPage = GetAdventureForPage(appInfo);210 var lstAdventure = appInfo.AdventureInfo.Payload.Select(x => $"#{x}").ToHashSet();211 var AmountPages = appInfo.DragonPageInfo.Payload.TotalPage;212 for (int page = 0; page < AmountPages; page++)213 {214 //foreach (var item in lstPage)215 //{216 var lstTemp = await GetCardItemsAsync(page + 1);217 if (lstTemp.Count < 1) break;218 for (int i = 0; i < lstTemp.Count; i++)219 {220 var card = lstTemp[i];221 try222 {223 if (card != null && lstAdventure.Contains(card.Id.Trim()))224 {225 await Task.Delay(2000);...
Program.cs
Source:Program.cs
...39 catch (Exception ex)40 {41 Console.WriteLine($"FAILED: error parsing response - {ex.Message}");42 }43 var devicePayloads = json.Extensions44 .Where(extension => extension.Type == "emulated-device")45 .Select(extension => extension.Device)46 .ToArray();47 var devices = new List<OutputDevice>();48 foreach (var payload in devicePayloads)49 {50 string[] names;51 if (payload.Title == "iPhone 6/7/8")52 {53 names = new[] { "iPhone 6", "iPhone 7", "iPhone 8" };54 }55 else if (payload.Title == "iPhone 6/7/8 Plus")56 {57 names = new[] { "iPhone 6 Plus", "iPhone 7 Plus", "iPhone 8 Plus" };58 }59 else if (payload.Title == "iPhone 5/SE")60 {61 names = new[] { "iPhone 5", "iPhone SE" };62 }63 else64 {65 names = new[] { payload.Title };66 }67 foreach (var name in names)68 {69 var device = CreateDevice(chromeVersion, name, payload, false);70 var landscape = CreateDevice(chromeVersion, name, payload, true);71 devices.Add(device);72 if (landscape.Viewport.Width != device.Viewport.Width || landscape.Viewport.Height != device.Viewport.Height)73 {74 devices.Add(landscape);75 }76 }77 }78 devices.RemoveAll(device => !device.Viewport.IsMobile);79 devices.Sort((a, b) => a.Name.CompareTo(b.Name));80 WriteDeviceDescriptors(devices);81 WriteDeviceDescriptorName(devices);82 }83 static void WriteDeviceDescriptors(IEnumerable<OutputDevice> devices)84 {85 var builder = new StringBuilder();86 var begin = @"using System.Collections.Generic;87namespace PuppeteerSharp.Mobile88{89 /// <summary>90 /// Device descriptors.91 /// </summary>92 public class DeviceDescriptors93 {94 private static readonly Dictionary<DeviceDescriptorName, DeviceDescriptor> Devices = new Dictionary<DeviceDescriptorName, DeviceDescriptor>95 {96";97 var end = @"98 };99 100 /// <summary>101 /// Get the specified device description.102 /// </summary>103 /// <returns>The device descriptor.</returns>104 /// <param name=""name"">Device Name.</param>105 public static DeviceDescriptor Get(DeviceDescriptorName name) => Devices[name];106 }107}";108 builder.Append(begin);109 builder.AppendJoin(",\n", devices.Select(GenerateCsharpFromDevice));110 builder.Append(end);111 File.WriteAllText(deviceDescriptorsOutput, builder.ToString());112 }113 static void WriteDeviceDescriptorName(IEnumerable<OutputDevice> devices)114 {115 var builder = new StringBuilder();116 var begin = @"namespace PuppeteerSharp.Mobile117{118 /// <summary>119 /// Device descriptor name.120 /// </summary>121 public enum DeviceDescriptorName122 {";123 var end = @"124 }125}";126 builder.Append(begin);127 builder.AppendJoin(",", devices.Select(device =>128 {129 return $@"130 /// <summary>131 /// {device.Name}132 /// </summary>133 {DeviceNameToEnumValue(device)}";134 }));135 builder.Append(end);136 File.WriteAllText(deviceDescriptorNameOutput, builder.ToString());137 }138 static string GenerateCsharpFromDevice(OutputDevice device)139 {140 var w = string.Empty;141 return $@" [DeviceDescriptorName.{DeviceNameToEnumValue(device)}] = new DeviceDescriptor142 {{143 Name = ""{device.Name}"",144 UserAgent = ""{device.UserAgent}"",145 ViewPort = new ViewPortOptions146 {{147 Width = {device.Viewport.Width},148 Height = {device.Viewport.Height},149 DeviceScaleFactor = {device.Viewport.DeviceScaleFactor},150 IsMobile = {device.Viewport.IsMobile.ToString().ToLower()},151 HasTouch = {device.Viewport.HasTouch.ToString().ToLower()},152 IsLandscape = {device.Viewport.IsLandscape.ToString().ToLower()}153 }}154 }}";155 }156 static string DeviceNameToEnumValue(OutputDevice device)157 {158 var output = new StringBuilder();159 output.Append(char.ToUpper(device.Name[0]));160 for (var i = 1; i < device.Name.Length; i++)161 {162 if (char.IsWhiteSpace(device.Name[i]))163 {164 output.Append(char.ToUpper(device.Name[i + 1]));165 i++;166 }167 else168 {169 output.Append(device.Name[i]);170 }171 }172 return output.ToString();173 }174 static OutputDevice CreateDevice(string chromeVersion, string deviceName, RootObject.Device descriptor, bool landscape)175 {176 var devicePayload = LoadFromJSONV1(descriptor);177 var viewportPayload = landscape ? devicePayload.Horizontal : devicePayload.Vertical;178 return new OutputDevice179 {180 Name = deviceName + (landscape ? " landscape" : string.Empty),181 UserAgent = devicePayload.UserAgent.Replace("%s", chromeVersion),182 Viewport = new OutputDevice.OutputDeviceViewport183 {184 Width = viewportPayload.Width,185 Height = viewportPayload.Height,186 DeviceScaleFactor = devicePayload.DeviceScaleFactor,187 IsMobile = devicePayload.Capabilities.Contains("mobile"),188 HasTouch = devicePayload.Capabilities.Contains("touch"),189 IsLandscape = landscape190 }191 };192 }193 static DevicePayload LoadFromJSONV1(RootObject.Device json) => new DevicePayload194 {195 Type = json.Type,196 UserAgent = json.UserAgent,197 Capabilities = json.Capabilities.ToHashSet(),198 DeviceScaleFactor = json.Screen.DevicePixelRatio,199 Horizontal = new ViewportPayload200 {201 Height = json.Screen.Horizontal.Height,202 Width = json.Screen.Horizontal.Width203 },204 Vertical = new ViewportPayload205 {206 Height = json.Screen.Vertical.Height,207 Width = json.Screen.Vertical.Width208 }209 };210 static Task<string> HttpGET(string url) => new HttpClient().GetStringAsync(url);211 }212}...
FrameManager.cs
Source:FrameManager.cs
...39 case "Page.frameAttached":40 OnFrameAttached(e.MessageData.frameId.ToString(), e.MessageData.parentFrameId.ToString());41 break;42 case "Page.frameNavigated":43 OnFrameNavigated(((JObject)e.MessageData.frame).ToObject<FramePayload>());44 break;45 case "Page.frameDetached":46 OnFrameDetached(e.MessageData.frameId.ToString());47 break;48 case "Runtime.executionContextCreated":49 OnExecutionContextCreated(new ContextPayload(e.MessageData.context));50 break;51 case "Runtime.executionContextDestroyed":52 OnExecutionContextDestroyed((int)e.MessageData.executionContextId);53 break;54 case "Runtime.executionContextsCleared":55 OnExecutionContextsCleared();56 break;57 case "Page.lifecycleEvent":58 OnLifeCycleEvent(e);59 break;60 default:61 break;62 }63 }64 private void OnLifeCycleEvent(MessageEventArgs e)65 {66 if (Frames.ContainsKey(e.MessageData.frameId.ToString()))67 {68 Frame frame = Frames[e.MessageData.frameId.ToString()];69 frame.OnLifecycleEvent(e.MessageData.loaderId.ToString(), e.MessageData.name.ToString());70 LifecycleEvent?.Invoke(this, new FrameEventArgs(frame));71 }72 }73 private void OnExecutionContextsCleared()74 {75 foreach (var context in _contextIdToContext.Values)76 {77 RemoveContext(context);78 }79 _contextIdToContext.Clear();80 }81 private void OnExecutionContextDestroyed(int executionContextId)82 {83 _contextIdToContext.TryGetValue(executionContextId, out var context);84 if (context != null)85 {86 _contextIdToContext.Remove(executionContextId);87 RemoveContext(context);88 }89 }90 public JSHandle CreateJsHandle(int contextId, dynamic remoteObject)91 {92 _contextIdToContext.TryGetValue(contextId, out var storedContext);93 if (storedContext == null)94 {95 _logger.LogError("INTERNAL ERROR: missing context with id = {ContextId}", contextId);96 }97 if (remoteObject.subtype == "node")98 {99 return new ElementHandle(storedContext, _client, remoteObject, _page);100 }101 return new JSHandle(storedContext, _client, remoteObject);102 }103 private void OnExecutionContextCreated(ContextPayload contextPayload)104 {105 var context = new ExecutionContext(_client, contextPayload,106 remoteObject => CreateJsHandle(contextPayload.Id, remoteObject));107 _contextIdToContext[contextPayload.Id] = context;108 var frame = !string.IsNullOrEmpty(context.FrameId) ? Frames[context.FrameId] : null;109 if (frame != null && context.IsDefault)110 {111 frame.SetDefaultContext(context);112 }113 }114 private void OnFrameDetached(string frameId)115 {116 if (Frames.ContainsKey(frameId))117 {118 RemoveFramesRecursively(Frames[frameId]);119 }120 }121 private void OnFrameNavigated(FramePayload framePayload)122 {123 var isMainFrame = string.IsNullOrEmpty(framePayload.ParentId);124 var frame = isMainFrame ? MainFrame : Frames[framePayload.Id];125 Contract.Assert(isMainFrame || frame != null, "We either navigate top level or have old version of the navigated frame");126 // Detach all child frames first.127 if (frame != null)128 {129 while (frame.ChildFrames.Count > 0)130 {131 RemoveFramesRecursively(frame.ChildFrames[0]);132 }133 }134 // Update or create main frame.135 if (isMainFrame)136 {137 if (frame != null)138 {139 // Update frame id to retain frame identity on cross-process navigation.140 if (frame.Id != null)141 {142 Frames.Remove(frame.Id);143 }144 frame.Id = framePayload.Id;145 }146 else147 {148 // Initial main frame navigation.149 frame = new Frame(this._client, this._page, null, framePayload.Id);150 }151 Frames[framePayload.Id] = frame;152 MainFrame = frame;153 }154 // Update frame payload.155 frame.Navigated(framePayload);156 FrameNavigated?.Invoke(this, new FrameEventArgs(frame));157 }158 private void RemoveContext(ExecutionContext context)159 {160 var frame = !string.IsNullOrEmpty(context.FrameId) ? Frames[context.FrameId] : null;161 if (frame != null && context.IsDefault)162 {163 frame.SetDefaultContext(null);164 }165 }166 private void RemoveFramesRecursively(Frame frame)167 {168 while (frame.ChildFrames.Count > 0)169 {...
CaptureService.cs
Source:CaptureService.cs
...50 await e.Request.ContinueAsync();51 return;52 }53 //54 var payload = new Payload()55 {56 Headers = new Dictionary<string, string>{{"Content-Type", "application/x-www-form-urlencoded"}},57 Url = url,58 Method = HttpMethod.Post,59 PostData = String.Join("&",60 keyValuePairs.AllKeys.Select(a => a + "=" + HttpUtility.UrlEncode(keyValuePairs[a])))61 };62 await e.Request.ContinueAsync(payload);63 await Console.Out.WriteLineAsync($"REQUEST: {e.Request.Method} {e.Request.Url} {payload.PostData}");64 };65 page.Response += async (sender, e) =>66 {67 await Console.Out.WriteLineAsync($"RESPONSE: {e.Response.Url} -({e.Response.Request.Method}) {e.Response.Status:d} {e.Response.StatusText}");68 };...
Payload.cs
Source:Payload.cs
...7using PuppeteerSharp.Helpers;8namespace PuppeteerSharp9{10 /// <summary>11 /// Payload information.12 /// </summary>13 public class Payload14 {15 internal Payload()16 {17 Headers = new Dictionary<string, object>();18 }1920 /// <summary>21 /// Gets or sets the HTTP method.22 /// </summary>23 /// <value>HTTP method.</value>24 [JsonProperty("method"), JsonConverter(typeof(HttpMethodConverter))]25 public HttpMethod Method { get; internal set; }26 /// <summary>27 /// Gets or sets the post data.28 /// </summary>29 /// <value>The post data.</value>30 [JsonProperty("postData")]31 public object PostData { get; internal set; }32 /// <summary>33 /// Gets or sets the HTTP headers.34 /// </summary>35 /// <value>HTTP headers.</value>36 [JsonProperty("headers")]37 public Dictionary<string, object> Headers { get; internal set; }38 /// <summary>39 /// Gets or sets the URL.40 /// </summary>41 /// <value>The URL.</value>42 [JsonProperty("url")]43 public string Url { get; internal set; }44 [JsonIgnore]45 internal string Hash46 {47 get48 {49 var normalizedUrl = Url;50 try51 {52 // Decoding is necessary to normalize URLs.53 // The method will throw if the URL is malformed. In this case,54 // consider URL to be normalized as-is.55 normalizedUrl = HttpUtility.UrlDecode(Url);56 }57 catch58 {59 }60 var hash = new Payload61 {62 Url = Url,63 Method = Method,64 PostData = PostData65 };66 if (!normalizedUrl.StartsWith("data:", StringComparison.Ordinal))67 {68 foreach (var item in Headers.OrderBy(kv => kv.Key))69 {70 if (item.Key.Equals("Accept", StringComparison.OrdinalIgnoreCase)71 || item.Key.Equals("Referer", StringComparison.OrdinalIgnoreCase)72 || item.Key.Equals("X-DevTools-Emulate-Network-Conditions-Client-Id", StringComparison.OrdinalIgnoreCase))73 {74 continue;...
FrameTree.cs
Source:FrameTree.cs
...12 }13 internal FrameTree(JToken frameTree)14 {15 var frame = frameTree[MessageKeys.Frame];16 Frame = new FramePayload17 {18 Id = frame[MessageKeys.Id].AsString(),19 ParentId = frame[MessageKeys.ParentId].AsString(),20 Name = frame[MessageKeys.Name].AsString(),21 Url = frame[MessageKeys.Url].AsString()22 };23 Childs = new List<FrameTree>();24 LoadChilds(this, frameTree);25 }26 #region Properties27 internal FramePayload Frame { get; set; }28 internal List<FrameTree> Childs { get; set; }29 #endregion30 #region Private Functions31 private void LoadChilds(FrameTree frame, JToken frameTree)32 {33 var childFrames = frameTree[MessageKeys.ChildFrames];34 if (childFrames != null)35 {36 foreach (var item in childFrames)37 {38 var childFrame = item[MessageKeys.Frame];39 var newFrame = new FrameTree40 {41 Frame = new FramePayload42 {43 Id = childFrame[MessageKeys.Id].AsString(),44 ParentId = childFrame[MessageKeys.ParentId].AsString(),45 Url = childFrame[MessageKeys.Url].AsString()46 }47 };48 if ((item as JObject)[MessageKeys.ChildFrames] != null)49 {50 LoadChilds(newFrame, item);51 }52 frame.Childs.Add(newFrame);53 }54 }55 }...
BindingCalledResponse.cs
Source:BindingCalledResponse.cs
...6 internal class BindingCalledResponse7 {8 private string _payloadJson;9 public int ExecutionContextId { get; set; }10 public BindingCalledResponsePayload BindingPayload { get; set; }11 public string Payload12 {13 get => _payloadJson;14 set15 {16 _payloadJson = value;17 var json = JsonConvert.DeserializeObject(_payloadJson, JsonHelper.DefaultJsonSerializerSettings) as JObject;18 BindingPayload = json.ToObject<BindingCalledResponsePayload>(true);19 BindingPayload.JsonObject = json;20 }21 }22 internal class BindingCalledResponsePayload23 {24 public string Name { get; set; }25 public JToken[] Args { get; set; }26 public int Seq { get; set; }27 public JObject JsonObject { get; set; }28 }29 }30}...
ContextPayload.cs
Source:ContextPayload.cs
1namespace PuppeteerSharp2{3 internal class ContextPayload4 {5 internal ContextPayload(dynamic context)6 {7 Id = context.id;8 AuxData = context.auxData.ToObject<ContextPayloadAuxData>();9 }10 internal int Id { get; }11 internal ContextPayloadAuxData AuxData { get; }12 }13}...
Payload
Using AI Code Generation
1{2 Stream = new MemoryStream(Encoding.UTF8.GetBytes("Hello world"))3};4var json = JsonConvert.SerializeObject(payload, new JsonSerializerSettings5{6 ContractResolver = new CamelCasePropertyNamesContractResolver()7});8var json = @"{9}";10var payload = JsonConvert.DeserializeObject<Payload>(json);11{12 Stream = new MemoryStream(Encoding.UTF8.GetBytes("Hello world"))13};14var json = JsonConvert.SerializeObject(payload, new JsonSerializerSettings15{16 ContractResolver = new CamelCasePropertyNamesContractResolver()17});18var payload2 = JsonConvert.DeserializeObject<Payload>(json);19var json = @"{20}";21var payload = JsonConvert.DeserializeObject<Payload>(json);22var json2 = JsonConvert.SerializeObject(payload, new JsonSerializerSettings23{24 ContractResolver = new CamelCasePropertyNamesContractResolver()25});26{27 Stream = new MemoryStream(Encoding.UTF8.GetBytes("Hello world"))28};29var json = JsonConvert.SerializeObject(payload, new JsonSerializerSettings30{31 ContractResolver = new CamelCasePropertyNamesContractResolver()32});33var payload2 = JsonConvert.DeserializeObject<Payload>(json);34var json2 = JsonConvert.SerializeObject(payload2, new JsonSerializerSettings35{
Payload
Using AI Code Generation
1var payload = new Payload();2payload.Html = "<html><body>test</body></html>";3payload.Headers = new Dictionary<string, string>();4payload.Headers.Add("key1", "value1");5payload.Headers.Add("key2", "value2");6payload.Cookies = new List<CookieParam>();7payload.Cookies.Add(new CookieParam() { Name = "name1", Value = "value1", Domain = "www.google.com" });8payload.Cookies.Add(new CookieParam() { Name = "name2", Value = "value2", Domain = "www.google.com" });9payload.Options = new Dictionary<string, object>();10payload.Options.Add("waitUntil", new string[] { "networkidle2" });11payload.Options.Add("timeout", 30000);12payload.Options.Add("viewport", new { width = 1920, height = 1080 });13payload.Options.Add("userAgent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36");14payload.Options.Add("deviceScaleFactor", 1);15payload.Options.Add("isMobile", false);16payload.Options.Add("hasTouch", false);17payload.Options.Add("isLandscape", false);18var json = JsonConvert.SerializeObject(payload);19var bytes = Encoding.UTF8.GetBytes(json);20var base64 = Convert.ToBase64String(bytes);21var result = await PuppeteerSharpHelper.GeneratePdf(base64);22var pdfBytes = Convert.FromBase64String(result);23File.WriteAllBytes("C:\\temp\\test.pdf", pdfBytes);24var payload = new Payload();25payload.Html = "<html><body>test</body></html>";26payload.Headers = new Dictionary<string, string>();27payload.Headers.Add("key1", "value1");28payload.Headers.Add("key2", "value2");29payload.Cookies = new List<CookieParam>();30payload.Cookies.Add(new CookieParam() { Name = "name1", Value = "value1", Domain = "www.google.com" });31payload.Cookies.Add(new CookieParam() { Name = "name2", Value = "value2", Domain = "www.google.com" });32payload.Options = new Dictionary<string, object>();33payload.Options.Add("
Payload
Using AI Code Generation
1var payload = new Payload();2payload.SetProperty("foo", "bar");3var response = await page.EvaluateFunctionAsync<Payload>("(payload) => payload", payload);4var payload = new Payload();5payload.SetProperty("foo", "bar");6var response = await page.EvaluateFunctionAsync<Payload>("(payload) => payload", payload);7var payload = new Payload();8payload.SetProperty("foo", "bar");9var response = await page.EvaluateFunctionAsync<Payload>("(payload) => payload", payload);10var payload = new Payload();11payload.SetProperty("foo", "bar");12var response = await page.EvaluateFunctionAsync<Payload>("(payload) => payload", payload);13var payload = new Payload();14payload.SetProperty("foo", "bar");15var response = await page.EvaluateFunctionAsync<Payload>("(payload) => payload", payload);16var payload = new Payload();17payload.SetProperty("foo", "bar");18var response = await page.EvaluateFunctionAsync<Payload>("(payload) => payload", payload);19var payload = new Payload();20payload.SetProperty("foo", "bar");21var response = await page.EvaluateFunctionAsync<Payload>("(payload) => payload", payload);22var payload = new Payload();23payload.SetProperty("foo", "bar");24var response = await page.EvaluateFunctionAsync<Payload>("(payload) => payload", payload);
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!!