Best Puppeteer-sharp code snippet using PuppeteerSharp.Page.WaitForTimeoutAsync
PageServer.cs
Source:PageServer.cs
...172 await page.EvaluateFunctionOnNewDocumentAsync("function(){Object.defineProperty(navigator, 'webdriver', {get: () => undefined})}");173 DeviceDescriptor deviceOptions = Puppeteer.Devices.GetValueOrDefault(DeviceDescriptorName.IPhone7);174 await page.EmulateAsync(deviceOptions);175 await page.GoToAsync(Url);176 await page.WaitForTimeoutAsync(500);177 await GetPhoneCode(Phone, page);178 var seven = await page.EvaluateExpressionAsync("document.querySelectorAll('button[report-eventid=MLoginRegister_SMSReceiveCode]')[0].innerText");179 await page.ClickAsync("button[report-eventid='MLoginRegister_SMSReceiveCode']");180 await page.ClickAsync("input[type=checkbox]");181 await page.WaitForTimeoutAsync(500);182 string js = "document.body.outerText";183 var pageouterText = await page.EvaluateExpressionAsync(js);184 var pagetext = pageouterText.ToString();185 var data = await getCount(qlkey);186 if (pagetext.Contains("å®å
¨éªè¯") && !pagetext.Contains("éªè¯æå"))187 {188 Console.WriteLine(Phone + "å®å
¨éªè¯");189 // await PageClose(Phone);190 result.data = new { Status = 666,ckcount = data.ckcount, tabcount = data.tabcount };191 result.message = "åºç°å®å
¨éªè¯,";192 return result;193 }194 if (pagetext.Contains("çä¿¡éªè¯ç åé次æ°å·²è¾¾ä¸é"))195 {196 await PageClose(Phone);197 result.data = new { Status = 505, pagetext = pagetext };198 result.message = "对ä¸èµ·ï¼çä¿¡éªè¯ç åé次æ°å·²è¾¾ä¸éï¼è¯·24å°æ¶ååè¯ã";199 return result;200 }201 if (pagetext.Contains("该ææºå·æªæ³¨åï¼å°ä¸ºæ¨ç´æ¥æ³¨åã"))202 {203 await PageClose(Phone);204 result.data = new { Status = 501 };205 result.message = "该ææºå·æªæ³¨å";206 return result;207 }208 Console.WriteLine(" ææºï¼" + Phone + " tabe å建 æ¶é´:" + DateTime.Now.ToString());209 System.Timers.Timer timer = new System.Timers.Timer(60000 * 3);210 timer.Elapsed += new System.Timers.ElapsedEventHandler(async (s, e) =>211 {212 Console.WriteLine(" ææºï¼" + Phone + " tabe èªå¨åæ¶ æ¶é´:" + DateTime.Now.ToString());213 Delpage(Phone, page);214 await page.CloseAsync();215 var oldpage = GetPage();216 if (oldpage == null)217 {218 await browser.CloseAsync();219 }220 timer.Dispose();221 });222 timer.AutoReset = false;223 timer.Start();224 225 result.data = new { ckcount = data.ckcount, tabcount = data.tabcount };226 result.success = true;227 return result;228 }229 public async Task PageClose(string Phone)230 {231 var page = GetPage(Phone);232 if (page != null)233 {234 Delpage(Phone, page);235 var browser = page.Browser;236 await page.CloseAsync();237 var oldpage = GetPage();238 if (oldpage == null)239 {240 await browser.CloseAsync();241 }242 }243 }244 public async Task ReSendSmSCode(string Phone)245 {246 var page = GetPage(Phone);247 if (page == null) throw new Exception("页é¢æªæ¾å°,å¯è½è¶
æ¶åæ¶äº.请å·æ°é¡µé¢éæ°ç»å½");248 await GetPhoneCode(Phone, page);249 }250 public async Task<ResultModel<object>> VerifyCode(int qlkey, string Phone, string Code)251 {252 try253 {254 ResultModel<object> result = ResultModel<object>.Create(false, "");255 var qlconfig = _mainConfig.GetConfig(qlkey);256 if (qlconfig == null)257 {258 result.message = "æªæ¾å°ç¸åºçæå¡å¨é
ç½®ã请å·æ°é¡µé¢ååè¯";259 result.data = new { Status = 404 };260 return result;261 }262 Page page = GetPage(Phone);263 if (page == null)264 {265 result.message = "æªæ¾å°å½åå·ç çç½é¡µè¯·ç¨ååè¯,æè
ç½é¡µè¶
è¿3åé已被åæ¶";266 result.data = new { Status = 404 };267 return result;268 }269 await SetCode(Code, page);270 Console.WriteLine("è¾å
¥éªè¯ç " + Code);271 Console.WriteLine(page.Url);272 await page.ClickAsync("a[report-eventid='MLoginRegister_SMSLogin']");273 // 274 await page.WaitForTimeoutAsync(2500);275 string js = "document.body.outerText";276 var pageouterText = await page.EvaluateExpressionAsync(js);277 var pagetext = pageouterText.ToString();278 // Console.WriteLine(pagetext.ToString());279 if (pagetext.Contains("éªè¯ç è¾å
¥é误"))280 {281 result.message = "éªè¯ç è¾å
¥é误";282 return result;283 }284 if (pagetext.Contains("éªè¯ç é误å¤æ¬¡ï¼è¯·éæ°è·å"))285 {286 await PageClose(Phone);287 result.data = new { Status = 501 };288 result.message = "éªè¯ç é误å¤æ¬¡,请è¿ä¸åéä¹ååæ¥ã";289 return result;290 }291 if (pagetext.Contains("该ææºå·æªæ³¨åï¼å°ä¸ºæ¨ç´æ¥æ³¨åã"))292 {293 await PageClose(Phone);294 result.data = new { Status = 501 };295 result.message = "该ææºå·æªæ³¨å";296 return result;297 }298 await page.WaitForTimeoutAsync(2500);299 var cookies = await page.GetCookiesAsync();300 var CKkey = cookies.FirstOrDefault(x => x.Name == "pt_key");301 var CKpin = cookies.FirstOrDefault(x => x.Name == "pt_pin");302 if (CKkey == null || CKpin == null)303 {304 await PageClose(Phone);305 result.message = "è·åCookie失败ï¼è¯·éè¯";306 result.data = new { Status = 404 };307 return result;308 }309 int MAXCount = qlconfig.QL_CAPACITY;310 var CCookie = CKkey.Name + "=" + CKkey.Value + ";" + CKpin.Name + "=" + CKpin.Value + ";";311 var Nickname = "";312 Nickname = await GetNickname(CCookie);313 JArray data = await qlconfig.GetEnv();314 var env = data.FirstOrDefault(x => x["value"].ToString().Contains("pt_pin=" + CKpin.Value + ";"));315 var QLCount = data.Count;316 317 string QLId = "";318 string timestamp = "";319 if (env == null)320 {321 if (QLCount >= MAXCount)322 {323 result.message = "ä½ æ¥æäºï¼æ²¡æå¤ä½çä½ç½®äº";324 result.data = new { Status = 501 };325 return result;326 }327 328 var addresult = await qlconfig.AddEnv(CCookie, Nickname);329 JObject addUser = (JObject)addresult.data[0];330 QLId = addUser["_id"].ToString();331 timestamp = addUser["timestamp"].ToString();332 }333 else334 {335 QLId = env["_id"].ToString();336 if(env["remarks"] != null)337 Nickname = env["remarks"].ToString();338 339 var upresult = await qlconfig.UpdateEnv(CCookie, QLId, Nickname);340 timestamp = upresult.data["timestamp"].ToString();341 }342 var qin = await getCount(qlkey);343 await PageClose(Phone);344 result.success = true;345 result.data = new { qlid = QLId, nickname = Nickname, timestamp = timestamp, remarks = Nickname, qlkey = qlconfig.QLkey, ckcount = qin.ckcount, tabcount = qin.tabcount };346 return result;347 }catch(Exception e)348 {349 Console.WriteLine(e.ToString());350 throw e;351 }352 353 }354 public async Task<(int ckcount, int tabcount)> getCount(int qlkey)355 {356 var config = _mainConfig.GetConfig(qlkey);357 var qlcount = await config.GetEnvsCount();358 var ckcount = config.QL_CAPACITY - qlcount;359 string MaxTab = _mainConfig.MaxTab;360 var intabcount = GetPageCount();361 int tabcount = int.Parse(MaxTab) - intabcount;362 return (ckcount, tabcount);363 }364 private async Task Setphone(string phone, Page page)365 {366 string jq = @"document.querySelectorAll('input[report-eventid=MLoginRegister_SMSPhoneInput]')[0].value='';";367 await page.EvaluateExpressionAsync(jq);368 System.Threading.Thread.Sleep(500);369 await page.TypeAsync("input[report-eventid=MLoginRegister_SMSPhoneInput]", phone);370 System.Threading.Thread.Sleep(500);371 }372 private async Task<bool> GetPhoneCode(string Phone, Page page)373 {374 page = AddPage(Phone, page);375 await Setphone(Phone, page);376 var CodeBtn = await page.XPathAsync("//button[@report-eventid='MLoginRegister_SMSReceiveCode']");377 var CodeProperties = await CodeBtn[0].GetPropertiesAsync();378 var CodeBtnClasses = CodeProperties["_prevClass"].ToString().Split(" ");379 bool canSendCode = CodeBtnClasses.Contains("active");380 if (canSendCode)381 {382 return true;383 }384 else385 {386 await page.ReloadAsync();387 System.Threading.Thread.Sleep(500);388 return await GetPhoneCode(Phone, page);389 }390 }391 private long GetTime()392 {393 TimeSpan ts = DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1);//ToUniversalTime()转æ¢ä¸ºæ åæ¶åºçæ¶é´,å»æçè¯ç´æ¥å°±ç¨å京æ¶é´394 return (long)ts.TotalSeconds;395 }396 private async Task<string> GetNickname(string cookie)397 {398 try399 {400 var url = @"https://me-api.jd.com/user_new/info/GetJDUserInfoUnion?orgFlag=JD_PinGou_New&callSource=mainorder&channel=4&isHomewhite=0&sceneval=2&_=" + GetTime() + "&sceneval=2&g_login_type=1&g_ty=ls";401 using (HttpClient client = new HttpClient())402 {403 client.DefaultRequestHeaders.Add("Cookie", cookie);404 client.DefaultRequestHeaders.Add("Referer", "https://home.m.jd.com/myJd/newhome.action");405 client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36");406 client.DefaultRequestHeaders.Add("Host", "me-api.jd.com");407 var result = await client.GetAsync(url);408 string resultContent = result.Content.ReadAsStringAsync().Result;409 // Console.WriteLine(resultContent);410 JObject j = JObject.Parse(resultContent);411 // data?.userInfo.baseInfo.nickname412 return j["data"]["userInfo"]["baseInfo"]["nickname"].ToString();413 }414 }415 catch(Exception e)416 {417 return "æªç¥";418 }419 420 }421 private static async Task SetCode(string Code, Page page)422 {423 await page.ClickAsync("#authcode", new PuppeteerSharp.Input.ClickOptions { ClickCount = 3 });424 System.Threading.Thread.Sleep(500);425 await page.TypeAsync("#authcode", Code);426 System.Threading.Thread.Sleep(500);427 }428 public async Task<ResultModel<object>> AutoCaptcha(string Phone)429 {430 Console.WriteLine(Phone + "å®å
¨éªè¯ç ´è§£");431 var page = GetPage(Phone);432 var cpc_img = await page.QuerySelectorAsync("#cpc_img");433 var cpc_imgheader = await cpc_img.GetPropertyAsync("src");434 var cpc_imgsrc = await cpc_imgheader.JsonValueAsync();435 var small_img = await page.QuerySelectorAsync("#small_img");436 var small_imgheader = await small_img.GetPropertyAsync("src");437 var small_imgsrc = await small_imgheader.JsonValueAsync();438 string pattern = @"data:image.*base64,(.*)";439 Match m = Regex.Match(cpc_imgsrc.ToString(), pattern);440 var cpc_imgbase64 = m.Groups[1].ToString();441 Match m2 = Regex.Match(small_imgsrc.ToString(), pattern);442 var small_imgbase64 = m2.Groups[1].ToString();443 byte[] cpc_imgBytes = Convert.FromBase64String(cpc_imgbase64);444 byte[] small_imgbaseBytes = Convert.FromBase64String(small_imgbase64);445 Stream cpcstream = new MemoryStream(cpc_imgBytes);446 Stream smallstream = new MemoryStream(small_imgbaseBytes);447 var cpcmap = new Bitmap(new Bitmap(cpcstream));448 var smallmap = new Bitmap(new Bitmap(smallstream));449 var Rsct = cv.getOffsetX(cpcmap, smallmap);450 cpcmap.Dispose();451 cpcstream.Close();452 smallstream.Close();453 smallmap.Dispose();454 var list = cv.GetPoints2(Rsct);455 var slider = await page.WaitForXPathAsync("//div[@class='sp_msg']/img");456 var box = await slider.BoundingBoxAsync();457 await page.Mouse.MoveAsync(box.X, box.Y);458 await page.Mouse.DownAsync();459 Random r = new Random(Guid.NewGuid().GetHashCode());460 var Steps = r.Next(5, 15);461 foreach (var item in list)462 {463 await page.Mouse.MoveAsync(item.X, box.Y, new PuppeteerSharp.Input.MoveOptions { Steps = Steps });464 }465 await page.Mouse.UpAsync();466 await page.WaitForTimeoutAsync(1000);467 var html = await page.GetContentAsync();468 469 ResultModel<object> result = ResultModel<object>.Create(false, "");470 if (html.Contains("éæ°è·å"))471 {472 Console.WriteLine("éªè¯æå");473 result.success = true;474 }475 else476 {477 if (html.Contains("çä¿¡éªè¯ç åé次æ°å·²è¾¾ä¸é"))478 {479 await PageClose(Phone);480 result.data = new { Status = 505 };...
Default.aspx.cs
Source:Default.aspx.cs
...39 MarginOptions = margin40 };41 var page = await browser.NewPageAsync().ConfigureAwait(false);42 await page.GoToAsync("C:/Users/sonam/source/repos/WebApplication6/mazer-main/dist/table.html").ConfigureAwait(false);43 await page.WaitForTimeoutAsync(2000);44 await page.PdfAsync(output, pdfOptions).ConfigureAwait(false);45 var fileName2 = Server.MapPath("~/PDF/table-datatable.pdf");46 var output2 = "" + fileName2;47 var browser2 = await Puppeteer.LaunchAsync(new LaunchOptions48 {49 ExecutablePath = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",50 DefaultViewport = vp51 }).ConfigureAwait(false);52 53 var pdfOptions2 = new PdfOptions54 {55 Format = PaperFormat.A2,56 Landscape = true,57 PrintBackground = true,58 DisplayHeaderFooter = true,59 MarginOptions = margin60 };61 var page2 = await browser.NewPageAsync().ConfigureAwait(false);62 await page2.GoToAsync("C:/Users/sonam/source/repos/WebApplication6/mazer-main/dist/table-datatable.html").ConfigureAwait(false);63 await page2.WaitForTimeoutAsync(2000);64 await page2.PdfAsync(output2, pdfOptions).ConfigureAwait(false);65 var fileName3 = Server.MapPath("~/PDF/ui-chart-apexcharts.pdf");66 var output3 = "" + fileName3;67 var browser3 = await Puppeteer.LaunchAsync(new LaunchOptions68 {69 ExecutablePath = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",70 DefaultViewport = vp71 }).ConfigureAwait(false);72 var pdfOptions3 = new PdfOptions73 {74 Format = PaperFormat.A2,75 Landscape = true,76 PrintBackground = true,77 DisplayHeaderFooter=true,78 MarginOptions=margin79 };80 var page3 = await browser.NewPageAsync().ConfigureAwait(false);81 await page3.GoToAsync("C:/Users/sonam/source/repos/WebApplication6/mazer-main/dist/ui-chart-apexcharts.html").ConfigureAwait(false);82 //await page3.WaitForFunctionAsync("windows.innerWidth<1600");83 await page3.WaitForTimeoutAsync(2000);84 await page3.PdfAsync(output3, pdfOptions).ConfigureAwait(false);85 var fileName4 = Server.MapPath("~/PDF/component-card.pdf");86 var output4 = "" + fileName4;87 var browser4 = await Puppeteer.LaunchAsync(new LaunchOptions88 {89 ExecutablePath = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",90 DefaultViewport = vp91 }).ConfigureAwait(false);92 var pdfOptions4 = new PdfOptions93 {94 Format = PaperFormat.A2,95 Landscape = true,96 PrintBackground = true,97 DisplayHeaderFooter = true,98 MarginOptions = margin99 };100 var page4 = await browser.NewPageAsync().ConfigureAwait(false);101 await page4.GoToAsync("C:/Users/sonam/source/repos/WebApplication6/mazer-main/dist/component-card.html").ConfigureAwait(false);102 await page4.WaitForTimeoutAsync(2000);103 await page4.PdfAsync(output4, pdfOptions).ConfigureAwait(false);104 var fileName5 = Server.MapPath("~/PDF/component-pagination.pdf");105 var output5 = "" + fileName5;106 var browser5 = await Puppeteer.LaunchAsync(new LaunchOptions107 {108 ExecutablePath = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",109 DefaultViewport = vp110 }).ConfigureAwait(false);111 var pdfOptions5 = new PdfOptions112 {113 Format = PaperFormat.A2,114 Landscape = true,115 PrintBackground = true,116 DisplayHeaderFooter = true,117 MarginOptions = margin118 };119 var page5 = await browser.NewPageAsync().ConfigureAwait(false);120 await page5.GoToAsync("C:/Users/sonam/source/repos/WebApplication6/mazer-main/dist/component-pagination.html").ConfigureAwait(false);121 await page5.WaitForTimeoutAsync(2000);122 await page5.PdfAsync(output5, pdfOptions).ConfigureAwait(false);123 var fileName6 = Server.MapPath("~/PDF/component-progress.pdf");124 var output6 = "" + fileName6;125 var browser6 = await Puppeteer.LaunchAsync(new LaunchOptions126 {127 ExecutablePath = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",128 DefaultViewport = vp129 }).ConfigureAwait(false);130 var pdfOptions6 = new PdfOptions131 {132 Format = PaperFormat.A2,133 Landscape = true,134 PrintBackground = true,135 DisplayHeaderFooter = true,136 MarginOptions = margin137 };138 var page6 = await browser.NewPageAsync().ConfigureAwait(false);139 await page6.GoToAsync("C:/Users/sonam/source/repos/WebApplication6/mazer-main/dist/component-progress.html").ConfigureAwait(false);140 await page6.WaitForTimeoutAsync(2000);141 await page6.PdfAsync(output6, pdfOptions).ConfigureAwait(false);142 var fileName7 = Server.MapPath("~/PDF/form-element-checkbox.pdf");143 var output7 = "" + fileName7;144 var browser7 = await Puppeteer.LaunchAsync(new LaunchOptions145 {146 ExecutablePath = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",147 DefaultViewport = vp148 }).ConfigureAwait(false);149 var pdfOptions7 = new PdfOptions150 {151 Format = PaperFormat.A2,152 Landscape = true,153 PrintBackground = true,154 DisplayHeaderFooter = true,155 MarginOptions = margin156 };157 var page7 = await browser.NewPageAsync().ConfigureAwait(false);158 await page7.GoToAsync("C:/Users/sonam/source/repos/WebApplication6/mazer-main/dist/form-element-checkbox.html").ConfigureAwait(false);159 await page7.WaitForTimeoutAsync(2000);160 await page7.PdfAsync(output7, pdfOptions).ConfigureAwait(false);161 var fileName8 = Server.MapPath("~/PDF/ui-widgets-pricing.pdf");162 var output8 = "" + fileName8;163 var browser8 = await Puppeteer.LaunchAsync(new LaunchOptions164 {165 ExecutablePath = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",166 DefaultViewport = vp167 }).ConfigureAwait(false);168 var pdfOptions8 = new PdfOptions169 {170 Format = PaperFormat.A2,171 Landscape = true,172 PrintBackground = true,173 DisplayHeaderFooter = true,174 MarginOptions = margin175 };176 var page8 = await browser.NewPageAsync().ConfigureAwait(false);177 await page8.GoToAsync("C:/Users/sonam/source/repos/WebApplication6/mazer-main/dist/ui-widgets-pricing.html").ConfigureAwait(false);178 await page8.WaitForTimeoutAsync(2000);179 await page8.PdfAsync(output8, pdfOptions).ConfigureAwait(false);180 var pdfs = new List<PdfDocument>();181 pdfs.Add(PdfDocument.FromFile("C:/Users/sonam/source/repos/WebApplication6/WebApplication6/PDF/table.pdf"));182 pdfs.Add(PdfDocument.FromFile("C:/Users/sonam/source/repos/WebApplication6/WebApplication6/PDF/table-datatable.pdf"));183 pdfs.Add(PdfDocument.FromFile("C:/Users/sonam/source/repos/WebApplication6/WebApplication6/PDF/ui-chart-apexcharts.pdf"));184 pdfs.Add(PdfDocument.FromFile("C:/Users/sonam/source/repos/WebApplication6/WebApplication6/PDF/component-card.pdf"));185 pdfs.Add(PdfDocument.FromFile("C:/Users/sonam/source/repos/WebApplication6/WebApplication6/PDF/component-pagination.pdf"));186 pdfs.Add(PdfDocument.FromFile("C:/Users/sonam/source/repos/WebApplication6/WebApplication6/PDF/component-progress.pdf"));187 pdfs.Add(PdfDocument.FromFile("C:/Users/sonam/source/repos/WebApplication6/WebApplication6/PDF/form-element-checkbox.pdf"));188 pdfs.Add(PdfDocument.FromFile("C:/Users/sonam/source/repos/WebApplication6/WebApplication6/PDF/ui-widgets-pricing.pdf"));189 PdfDocument pdf = PdfDocument.Merge(pdfs);190 pdf.SaveAs("C:/Users/sonam/source/repos/WebApplication6/WebApplication6/PDF/merged.pdf");191 System.Diagnostics.Process.Start("C:/Users/sonam/source/repos/WebApplication6/WebApplication6/PDF/merged.pdf");192 }...
TwitterRegistration.cs
Source:TwitterRegistration.cs
...37 await FillBirtDate(page);38 if (!string.IsNullOrEmpty(_data.ErrMsg)) return;39 await FillAccount(page);40 await page.ClickAsync("div[role='button']");41 await page.WaitForTimeoutAsync(1500);42 var buttons = await page.QuerySelectorAllAsync("div[role='button']");43 if (buttons.Length >= 2) await buttons[1].ClickAsync();44 await page.WaitForTimeoutAsync(1500);45 buttons = await page.QuerySelectorAllAsync("div[role='button']");46 if (buttons.Length >= 4) await buttons[3].ClickAsync();47 buttons = await page.QuerySelectorAllAsync("div[role='button']");48 if (buttons.Length >= 6) await buttons[5].ClickAsync();49 if (!string.IsNullOrEmpty(_data.ErrMsg)) return;50 await FillSms(page);51 if (!string.IsNullOrEmpty(_data.ErrMsg)) return;52 buttons = await page.QuerySelectorAllAsync("div[role='button']");53 if (buttons.Length >= 2) await buttons[1].ClickAsync();54 await page.WaitForTimeoutAsync(500);55 try56 {57 var ePassword = await page.QuerySelectorAsync("input[name='password'");58 await ePassword.ClickAsync();59 await ePassword.TypeAsync(_data.Password, _typeOptions);60 await page.ClickAsync("div[role='button']");61 await page.WaitForTimeoutAsync(1500);62 await page.ClickAsync("div[role='button']");63 await page.WaitForTimeoutAsync(1500);64 await page.ClickAsync("div[role='button']");65 await page.WaitForTimeoutAsync(1500);66 await page.ClickAsync("div[role='button']");67 await page.WaitForTimeoutAsync(1500);68 await page.ClickAsync("div[role='button']");69 await page.WaitForTimeoutAsync(1500);70 await page.ClickAsync("div[role='button']");71 await page.WaitForTimeoutAsync(2500);72 //await page.WaitForNavigationAsync();73 _data.Success = true;74 }75 catch (Exception exception)76 {77 Log.Error($"{exception}");78 _data.ErrMsg = $"{exception}";79 }80 }81 private async Task FillPhone(Page page)82 {83 await page.WaitForTimeoutAsync(500);84 var ePhone = await page.QuerySelectorAsync("input[name='phone_number'");85 await ePhone.ClickAsync(new ClickOptions { ClickCount = 3 });86 await ePhone.TypeAsync(_data.Phone, _typeOptions);87 await page.WaitForTimeoutAsync(500);88 }89 private async Task FillAccount(Page page)90 {91 var eFullname = await page.QuerySelectorAsync("input[name='name'");92 await eFullname.ClickAsync();93 await eFullname.TypeAsync($"{_data.Firstname} {_data.Lastname}", _typeOptions);94 //var eUsername = await page.QuerySelectorAsync("input[name='username'");95 //await eUsername.ClickAsync();96 //await eUsername.TypeAsync(_data.AccountName, _typeOptions);97 //var ePassword = await page.QuerySelectorAsync("input[name='password'");98 //await ePassword.ClickAsync();99 //await ePassword.TypeAsync(_data.Password, _typeOptions);100 await page.WaitForTimeoutAsync(500);101 }102 private async Task FillBirtDate(Page page)103 {104 try105 {106 var elements = await page.QuerySelectorAllAsync("select[class]");107 var eMonth = elements[0];108 await eMonth.SelectAsync($"{_data.BirthDate.Month}");109 await page.WaitForTimeoutAsync(500);110 var eDay = elements[1];111 await eDay.SelectAsync($"{_data.BirthDate.Day}");112 await page.WaitForTimeoutAsync(500);113 var eYear = elements[2];114 await eYear.SelectAsync($"{_data.BirthDate.Year}");115 await page.WaitForTimeoutAsync(500);116 }117 catch (Exception exception)118 {119 Log.Error($"{exception}");120 _data.ErrMsg = $"{exception}";121 }122 }123 private async Task FillSms(Page page)124 {125 if (!string.IsNullOrEmpty(_data.ErrMsg)) return;126 var eSmsInput = await page.WaitForSelectorAsync("input[name='verfication_code']");127 if (eSmsInput != null)128 {129 var phoneNumberValidation = await _smsService.GetSmsValidation(_requestId);...
InstagramRegistration.cs
Source:InstagramRegistration.cs
...43 _data.Success = true;44 }45 private async Task FillPhone(Page page)46 {47 await page.WaitForTimeoutAsync(500);48 var ePhone = await page.QuerySelectorAsync("input[name='emailOrPhone'");49 await ePhone.ClickAsync(new ClickOptions { ClickCount = 3 });50 await ePhone.TypeAsync(_data.Phone, _typeOptions);51 await page.WaitForTimeoutAsync(500);52 }53 private async Task FillAccount(Page page)54 {55 if (!string.IsNullOrEmpty(_data.ErrMsg)) return;56 var eFullname = await page.QuerySelectorAsync("input[name='fullName'");57 await eFullname.ClickAsync();58 await eFullname.TypeAsync($"{_data.Firstname} {_data.Lastname}", _typeOptions);59 var eUsername = await page.QuerySelectorAsync("input[name='username'");60 await eUsername.ClickAsync();61 await eUsername.TypeAsync(_data.AccountName, _typeOptions);62 var ePassword = await page.QuerySelectorAsync("input[name='password'");63 await ePassword.ClickAsync();64 await ePassword.TypeAsync(_data.Password, _typeOptions);65 await page.WaitForTimeoutAsync(500);66 await ClickSubmit(page);67 await page.WaitForTimeoutAsync(1000);68 }69 private async Task FillBirtDate(Page page)70 {71 if (!string.IsNullOrEmpty(_data.ErrMsg)) return;72 try73 {74 var elements = await page.QuerySelectorAllAsync("select[title]");75 var eMonth = elements[0];76 await eMonth.SelectAsync($"{_data.BirthDate.Month}");77 await page.WaitForTimeoutAsync(500);78 var eDay = elements[1];79 await eDay.SelectAsync($"{_data.BirthDate.Day}");80 await page.WaitForTimeoutAsync(500);81 var eYear = elements[2];82 await eYear.SelectAsync($"{_data.BirthDate.Year}");83 await page.WaitForTimeoutAsync(1000);84 var buttons = await page.QuerySelectorAllAsync("button[type='button']");85 await buttons[1].ClickAsync();86 await page.WaitForTimeoutAsync(1000);87 }88 catch (Exception exception)89 {90 Log.Error($"{exception}");91 _data.ErrMsg = $"{exception}";92 }93 }94 private async Task FillSms(Page page)95 {96 if (!string.IsNullOrEmpty(_data.ErrMsg)) return;97 98 var eSmsInput = await page.WaitForSelectorAsync("input[name='confirmationCode']");99 if (eSmsInput != null)100 {101 var phoneNumberValidation = await _smsService.GetSmsValidation(_requestId);102 Log.Info($"phoneNumberValidation: {JsonConvert.SerializeObject(phoneNumberValidation)}");103 if (phoneNumberValidation != null)104 {105 await _smsService.SetSmsValidationSuccess(_requestId);106 // enter sms code107 await eSmsInput.TypeAsync(phoneNumberValidation.Code, _typeOptions);108 var buttons = await page.QuerySelectorAsync("button[type='button']");109 await buttons.ClickAsync();110 await page.WaitForTimeoutAsync(500);111 }112 else113 {114 _data.ErrMsg = BotMessages.PhoneNumberNotRecieveSms;115 await _smsService.SetNumberFail(_requestId);116 }117 }118 }119 private static async Task ClickSubmit(Page page)120 {121 var elSignUp = await page.QuerySelectorAsync("button[type=submit]");122 await elSignUp.ClickAsync();123 await page.WaitForTimeoutAsync(500);124 }125 }126}...
BadmintonClient.cs
Source:BadmintonClient.cs
...82 // Which causes Pupperteer to think it has successfully clicked on the button when it didn't83 84 // Click on Cart section finished button85 await page.WaitForSelectorAsync("#u3600_btnCheckout0");86 await page.WaitForTimeoutAsync(1000);87 await page.ClickAsync("#u3600_btnCheckout0");88 89 // Click on the Confirm button90 await page.WaitForSelectorAsync("#u3600_btnCartShoppingCompleteStep");91 await page.WaitForTimeoutAsync(1000);92 await page.ClickAsync("#u3600_btnCartShoppingCompleteStep");93 94 // Accept Terms & services95 await page.WaitForSelectorAsync("#u3600_chkElectronicPaymentCondition");96 await page.WaitForTimeoutAsync(1000);97 await page.ClickAsync("#u3600_chkElectronicPaymentCondition");98 99 // Click on the Confirm button100 await page.WaitForSelectorAsync("#u3600_btnCartPaymentCompleteStep");101 await page.WaitForTimeoutAsync(1000);102 await page.ClickAsync("#u3600_btnCartPaymentCompleteStep");103 }104 105 private async Task Login(Page page, BadmintonCredentials credentials)106 {107 try108 {109 await page.WaitForSelectorAsync("#formpr", new WaitForSelectorOptions110 {111 Timeout = 2000112 });113 } 114 catch (WaitTaskTimeoutException)115 {...
PostVk.cs
Source:PostVk.cs
...25 await page.GoToAsync($"https://vk.com/{vkGroup}");26 //await page.GoToAsync($"https://vk.com/club188446341");27 await page.WaitForSelectorAsync("div.submit_post_field", new WaitForSelectorOptions { Timeout = 5000 });28 await page.ClickAsync("div.submit_post_field");29 await page.WaitForTimeoutAsync(500);30 //await page.TypeAsync("div.submit_post_field", "45", new TypeOptions { Delay = 50 });31 await page.Keyboard.PressAsync($"{nameof(Key.Backspace)}");32 await page.Keyboard.PressAsync($"{nameof(Key.Backspace)}");33 await page.TypeAsync("div.submit_post_field", message, new TypeOptions { Delay = 50 });34 await page.WaitForTimeoutAsync(500);35 await page.ClickAsync("#send_post");36 await page.WaitForTimeoutAsync(500);37 //await page.Keyboard.PressAsync($"{nameof(Key.Enter)}");38 //Report($"{text}");39 }40 }41 }42 catch (Exception exception)43 {44 Error(exception.ToString());45 }46 }47 }48}...
AuthService.cs
Source:AuthService.cs
...24 "Try to authenticate...", username, new string(password.Select(t => '*').ToArray()));25 26 var page = await _browser.NewPageAsync();27 await page.GoToAsync("https://www.instagram.com/accounts/login/");28 await page.WaitForTimeoutAsync(timeout);29 await page.WaitForSelectorAsync(Consts.UserNameSelector);30 await page.FocusAsync(Consts.UserNameSelector);31 await page.Keyboard.TypeAsync(InstagramConfiguration.Username);32 await page.WaitForSelectorAsync(Consts.PasswordSelector);33 await page.FocusAsync(Consts.PasswordSelector);34 await page.Keyboard.TypeAsync(InstagramConfiguration.Password);35 await page.WaitForSelectorAsync(Consts.SubmitBtnSelector);36 await page.ClickAsync(Consts.SubmitBtnSelector);37 await page.WaitForTimeoutAsync(timeout);38 _logger.Information("Successfully authenticated!");39 return await page.GetCookiesAsync();40 }41 public void Dispose() => 42 _browser.Dispose();43 44 private static Browser InitBrowser() =>45 Puppeteer.LaunchAsync(new LaunchOptions {Headless = true, Args = new []{"--no-sandbox"}})46 .ConfigureAwait(false).GetAwaiter().GetResult();47 }48}...
Uber.cs
Source:Uber.cs
...12 public static async Task Login(string user, string password)13 {14 Console.WriteLine("Uber Login:" + user +",", password );15 await page.GoToAsync("https://partners.uber.com");16 await page.WaitForTimeoutAsync(2000);17 // Type into search box.18 await page.TypeAsync("#useridInput", user);19 Console.WriteLine("Uber Login End");20 await Util.GetInputAsync();21 }22 }23}...
WaitForTimeoutAsync
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static async Task Main(string[] args)7 {8 {9 };10 using (var browser = await Puppeteer.LaunchAsync(options))11 {12 using (var page = await browser.NewPageAsync())13 {14 await page.WaitForTimeoutAsync(5000);15 }16 }17 }18 }19}
WaitForTimeoutAsync
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 Console.WriteLine("Waiting for 10 seconds");14 await page.WaitForTimeoutAsync(10000);15 Console.WriteLine("Waited for 10 seconds");16 await browser.CloseAsync();17 }18 }19}20Recommended Posts: How to use the WaitForFunctionAsync() method of PuppeteerSharp.Page class in C#?21How to use the WaitForSelectorAsync() method of PuppeteerSharp.Page class in C#?22How to use the WaitForXPathAsync() method of PuppeteerSharp.Page class in C#?23How to use the WaitForNavigationAsync() method of PuppeteerSharp.Page class in C#?24How to use the WaitForRequestAsync() method of PuppeteerSharp.Page class in C#?25How to use the WaitForResponseAsync() method of PuppeteerSharp.Page class in C#?26How to use the WaitForSelectorAsync() method of PuppeteerSharp.Frame class in C#?27How to use the WaitForXPathAsync() method of PuppeteerSharp.Frame class in C#?28How to use the WaitForFunctionAsync() method of PuppeteerSharp.Frame class in C#?29How to use the WaitForSelectorAsync() method of PuppeteerSharp.ElementHandle class in C#?30How to use the WaitForXPathAsync() method of PuppeteerSharp.ElementHandle class in C#?31How to use the WaitForFunctionAsync() method of PuppeteerSharp.ElementHandle class in C#?32How to use the WaitForTimeoutAsync() method of PuppeteerSharp.Frame class in C#?33How to use the WaitForTimeoutAsync() method of PuppeteerSharp.ElementHandle class in C#?34How to use the WaitForTimeoutAsync() method of PuppeteerSharp.Browser class in C#?35How to use the WaitForTimeoutAsync() method of PuppeteerSharp.BrowserContext class in C#?36How to use the WaitForTimeoutAsync() method of PuppeteerSharp.Dialog class in C#?
WaitForTimeoutAsync
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 using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false }))10 using (var page = await browser.NewPageAsync())11 {12 var search = await page.WaitForSelectorAsync("input[name='q']");13 await search.TypeAsync("puppeteer-sharp");14 await search.PressAsync("Enter");15 await page.WaitForTimeoutAsync(3000);16 var results = await page.QuerySelectorAllAsync("div.g");17 foreach (var result in results)18 {19 var title = await result.QuerySelectorAsync("h3");20 Console.WriteLine(await title.EvaluateFunctionAsync<string>("node => node.innerText"));21 }22 }23 }24 }25}
WaitForTimeoutAsync
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static void Main(string[] args)7 {8 MainAsync().Wait();9 }10 static async Task MainAsync()11 {12 var options = new LaunchOptions { Headless = false };13 using (var browser = await Puppeteer.LaunchAsync(options))14 using (var page = await browser.NewPageAsync())15 {16 await page.WaitForTimeoutAsync(3000);17 await page.ScreenshotAsync("google.png");18 }19 }20 }21}22WaitForNavigationAsync() Method23using System;24using System.Threading.Tasks;25using PuppeteerSharp;26{27 {28 static void Main(string[] args)29 {30 MainAsync().Wait();31 }32 static async Task MainAsync()33 {34 var options = new LaunchOptions { Headless = false };35 using (var browser = await
WaitForTimeoutAsync
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static async Task Main(string[] args)7 {8 Console.WriteLine("Hello World!");9 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);10 var browser = await Puppeteer.LaunchAsync(new LaunchOptions11 {12 Args = new string[] { "--no-sandbox", "--disable-setuid-sandbox" }13 });14 var page = await browser.NewPageAsync();15 await page.WaitForTimeoutAsync(1000);16 await page.ScreenshotAsync("google.png");17 await browser.CloseAsync();18 }19 }20}21using System;22using System.Threading.Tasks;23using PuppeteerSharp;24{25 {26 static async Task Main(string[] args)27 {28 Console.WriteLine("Hello World!");29 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);30 var browser = await Puppeteer.LaunchAsync(new LaunchOptions31 {32 Args = new string[] { "--no-sandbox", "--disable-setuid-sandbox" }33 });34 var page = await browser.NewPageAsync();35 await page.WaitForNavigationAsync();36 await page.WaitForTimeoutAsync(1000);37 await page.ScreenshotAsync("google.png");38 await browser.CloseAsync();39 }40 }41}42using System;43using System.Threading.Tasks;44using PuppeteerSharp;45{46 {47 static async Task Main(string[] args)48 {49 Console.WriteLine("Hello World!");50 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);51 var browser = await Puppeteer.LaunchAsync(new LaunchOptions
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!!