Best Puppeteer-sharp code snippet using PuppeteerSharp.Frame.WaitForTimeoutAsync
Program.cs
Source:Program.cs
...189 await page.GoToAsync("https://www.google.com/");190 //AnsiConsole.WriteLine("å¼å§è·åè¾å
¥æ¡ç¦ç¹");191 //await page.ClickAsync("input[id='kw']");192 AnsiConsole.WriteLine("çå¾
ä¸ç§");193 await page.WaitForTimeoutAsync(1000);194 AnsiConsole.WriteLine("模æè¾å
¥ææ¬");195 await page.TypeAsync("input[class='gLFyf gsfi']", text);196 AnsiConsole.WriteLine("çå¾
ä¸ç§");197 await page.WaitForTimeoutAsync(1000);198 AnsiConsole.WriteLine("模ææä¸Enteré®ç");199 await page.Keyboard.PressAsync("Enter");200 await page.WaitForNavigationAsync(); //注æ å¦æ导èªåçäºåå å¿
须使ç¨çå¾
导èª201 var Content = await page.GetContentAsync(); //è·å页é¢å
容202 var yuRUbf = await page.QuerySelectorAllAsync("div[class='yuRUbf']"); //è·åclass为yuRUbfæædiv203 AnsiConsole.WriteLine($"è·åå°å:{yuRUbf.Length}æ¡æç´¢æ°æ®\n");204 foreach (var item in yuRUbf)205 {206 var Tittle = await item.QuerySelectorAllAsync(@"a>h3");207 var Url = await item.QuerySelectorAllAsync(@"a");208 var StrTittle = await Tittle[0].GetPropertyAsync("innerText");209 var StrUrl = await Url[0].GetPropertyAsync("href");210 AnsiConsole.WriteLine($"æ é¢:{StrTittle.ToString().Replace("JSHandle:", "")}\nå°å:{StrUrl.ToString().Replace("JSHandle:", "")}\n\n");211 }212 AnsiConsole.WriteLine("çå¾
ä¸ç§");213 await page.WaitForTimeoutAsync(3000);214 AnsiConsole.WriteLine("ç»æ");215 };216 };217 return true;218 }219 /// <summary>220 /// å½å¼å¤è¯¾ç¨ç®åçè§é¢çæç« 221 /// </summary>222 /// <returns></returns>223 public static async void Ouchn()224 {225 var CourseList = new Dictionary<string, Page>();226 var Task = new List<Task>();227 var Pages = await browser.PagesAsync(); //è·åå½åææpage228 Console.WriteLine($"请æç
§æç¨æ¥,è¦å
³éææçEdgeçé¢");229 Console.WriteLine($"课ç¨ç»æ请è¾å
¥exitéåºè¯¾ç¨,å¨è¯¾ç¨æªå®ææ¶ä¹å¯ä»¥è¾å
¥exitéåº");230 Console.WriteLine($"课ç¨ç»æ请è¾å
¥exitéåºè¯¾ç¨,å¨è¯¾ç¨æªå®ææ¶ä¹å¯ä»¥è¾å
¥exitéåº");231 Console.WriteLine($"课ç¨ç»æ请è¾å
¥exitéåºè¯¾ç¨,å¨è¯¾ç¨æªå®ææ¶ä¹å¯ä»¥è¾å
¥exitéåº");232 Thread.Sleep(1000 * 5);233 Console.WriteLine($"è·åå°å½åæµè§å¨é¡µé¢æ:{Pages.Length}个");234 if (Pages.Length > 0)235 {236 Console.WriteLine("å¼å§å¹é
ææé¾æ¥æ¯å¦ä¸ºå½å¼è¯¾ç¨é¡µé¢...");237 for (int i = 0; i < Pages.Length; i++)238 {239 var Page = Pages[i];240 var Url = Page.Url.ToString();241 var Name = await Page.GetTitleAsync();242 if (Regex.IsMatch(Url, @"http://([\w-]+\.)+[\w-]+(/[\w-./?%&=]*)?id=[0-9]*"))243 {244 Console.WriteLine($"å¹é
æå:({Name}){Url}");245 CourseList.Add(Name, Page);246 }247 }248 if (CourseList.Count > 0)249 {250 Console.WriteLine($"å¹é
å°ç¬¦åå½å¼è¯¾ç¨é¡µé¢æ»æ°:{CourseList.Count}个");251 }252 else253 {254 Console.WriteLine($"没æå¹é
å°ç¬¦åå½å¼è¯¾ç¨é¡µé¢,请è¾å
¥ä»»æé®éåº...");255 Console.ReadLine();256 }257 }258 else259 {260 Console.WriteLine($"å½åè·åå°é¡µé¢ä¸º0,请è¾å
¥ä»»æé®éåº...");261 Console.ReadLine();262 }263 Console.WriteLine($"\nå¼å§å建线ç¨...");264 foreach (var item in CourseList)265 {266 var Tas = new System.Threading.Tasks.Task(async () =>267 {268 var Links = await item.Value.QuerySelectorAllAsync("a[class='aalink']"); //è·å第ä¸ä¸ªé¡µé¢çææaæ ç¾class为aalinkç269 Console.WriteLine($"[课ç¨:{item.Key}]è·åå°{Links.Length}个é¾æ¥");270 async Task<bool> OpenLink(ElementHandle[] handles)271 {272 try273 {274 var r = new Random();275 for (int i = 0; i < Links.Length; i++)276 {277 var URL = await Links[i].GetPropertyAsync("href");278 if (URL.ToString().Replace("JSHandle:", "").Contains(""))279 {280 }281 var Page = await browser.NewPageAsync();282 await Page.GoToAsync(URL.ToString().Replace("JSHandle:", ""), new NavigationOptions() { });283 Console.WriteLine($"[{item.Key}]å½åæ£å¨æµè§ç¬¬{i}个é¾æ¥:{URL.ToString().Replace("JSHandle:", "")}");284 var s = r.Next(5, 10);285 Console.WriteLine($"[{item.Key}]çå¾
{s}ç§");286 await Page.WaitForTimeoutAsync(s * 1000);287 await Page.CloseAsync(new PageCloseOptions() { RunBeforeUnload = true });288 Console.WriteLine($"[{item.Key}]å
³é页é¢");289 Console.WriteLine($"å¼å§ä¸ä¸ä¸ª\n");290 }291 }292 catch293 {294 }295 return true;296 }297 await OpenLink(Links);298 Console.WriteLine($"[{item.Key}]å¦ä¹ ç»æ å·²å¦ä¹ {Links.Length}个é¾æ¥\n");299 });300 Task.Add(Tas);...
MailRuRegistration.cs
Source:MailRuRegistration.cs
...64 // await ClickSubmit(page);65 //}66 await SolveRecaptcha(page);67 // check phone call68 await page.WaitForTimeoutAsync(500);69 try70 {71 var phoneCall = await page.WaitForSelectorAsync("a[data-test-id=resend-callui-link", new WaitForSelectorOptions { Timeout = 70 * 1000 });72 if (phoneCall != null)73 {74 await page.WaitForTimeoutAsync(500);75 await phoneCall.ClickAsync(); // I haven't received a call - click link for sms76 }77 }78 catch { }79 await page.WaitForTimeoutAsync(500);80 await SolveRecaptcha(page);81 // check sms82 await page.WaitForTimeoutAsync(2000);83 var eSendSms = await page.QuerySelectorAsync("form input[type='number']");84 if(eSendSms==null) eSendSms = await page.QuerySelectorAsync("input[name=code]");85 // ÑодеÑжимое ÑÑÑаниÑÑ86 //var content = await page.GetContentAsync();87 //var filename = $"c:\\temp\\mailru_{DateTime.Now.Ticks}.txt";88 //File.WriteAllText(filename, content);89 if (eSendSms != null)90 {91 var phoneNumberValidation = await _smsService.GetSmsValidation(_requestId);92 Log.Info($"phoneNumberValidation: {JsonConvert.SerializeObject(phoneNumberValidation)}");93 if (phoneNumberValidation != null)94 {95 // enter sms code96 await eSendSms.TypeAsync(phoneNumberValidation.Code, _typeOptions);97 await ClickSubmit(page);98 await _smsService.SetSmsValidationSuccess(_requestId);99 }100 await page.WaitForTimeoutAsync(10000);101 var emailSuccess = await page.QuerySelectorAsync("i#PH_user-email");102 if (emailSuccess != null)103 {104 _data.Success = true;105 Log.Info($"emailSuccess: {JsonConvert.SerializeObject(_data)}");106 //await _smsService.SetSmsValidationSuccess(_requestId);107 await page.ClickAsync("button[data-test-id='onboarding-button-start']");108 }109 else110 {111 _data.ErrMsg = @"ÐÐµÑ Ð¿ÐµÑеÑ
ода на ÑÑÑаниÑÑ Ð·Ð°ÑегиÑÑÑиÑованного email";112 }113 await _smsService.SetSmsValidationSuccess(_requestId);114 }115 else116 {117 _data.ErrMsg = "No sms code navigate";118 }119 }120 private async Task RegistrateByEmail(Page page)121 {122 Log.Info(page.Url);123 await FillName(page);124 await FillBirthdate(page);125 await FillSex(page);126 await FillEmail(page);127 if (page.Url.Contains("light."))128 {129 await ClickSubmit(page);130 }131 await FillPassword(page);132 if (page.Url.Contains("light."))133 {134 await FillPhone(page);135 await page.WaitForTimeoutAsync(500);136 await ClickSubmit(page);137 }138 await FillAdditionalEmail(page);139 await page.WaitForTimeoutAsync(1500);140 await ClickSubmit(page);141 await FillPhone(page);142 await page.WaitForTimeoutAsync(1500);143 await ClickSubmit(page);144 await page.WaitForTimeoutAsync(2500);145 var elImgage = await page.QuerySelectorAsync("img.js-captcha-img");146 if (elImgage == null) elImgage = await page.QuerySelectorAsync("img[alt=Code]");147 if (elImgage != null)148 {149 var antiCaptchaOnlineApi = new AntiCaptchaOnlineApi();150 var antiCaptchaResult = antiCaptchaOnlineApi.SolveIm(await elImgage.ScreenshotBase64Async(new ScreenshotOptions { OmitBackground = true }));151 if (antiCaptchaResult.Success)152 {153 var eInputCaptcha = await page.QuerySelectorAsync("input[name='capcha']");154 if (eInputCaptcha == null) eInputCaptcha = await page.QuerySelectorAsync("input[data-test-id]");155 await eInputCaptcha.TypeAsync(antiCaptchaResult.Response, _typeOptions);156 await ClickSubmit(page);157 }158 await page.WaitForTimeoutAsync(15000);159 var emailSuccess = await page.QuerySelectorAsync("i#PH_user-email");160 if (emailSuccess != null)161 {162 _data.Success = true;163 Log.Info($"emailSuccess: {JsonConvert.SerializeObject(_data)}");164 await page.ClickAsync("button[data-test-id='onboarding-button-start']");165 }166 else167 {168 _data.ErrMsg = @"ÐÐµÑ Ð¿ÐµÑеÑ
ода на ÑÑÑаниÑÑ Ð·Ð°ÑегиÑÑÑиÑованного email";169 }170 }171 }172 #region Steps173 private async Task FillName(Page page)174 {175 if (page.Url.Contains("light."))176 {177 await page.TypeAsync("div[class*='firstname'] input", _data.Firstname, _typeOptions);178 await page.TypeAsync("div[class*='lastname'] input", _data.Lastname, _typeOptions);179 return;180 }181 var eFirstname = await page.QuerySelectorAsync("input[name^=firstname]");182 if (eFirstname == null) eFirstname = await page.QuerySelectorAsync("input[name=fname]");183 await eFirstname.TypeAsync(_data.Firstname, _typeOptions);184 var eLastname = await page.QuerySelectorAsync("input[name^=lastname]");185 if (eLastname == null) eLastname = await page.QuerySelectorAsync("input[name=lname]");186 await eLastname.TypeAsync(_data.Lastname, _typeOptions);187 }188 private async Task FillBirthdate(Page page)189 {190 if (page.Url.Contains("light."))191 {192 await page.ClickAsync("select[class*='day'");193 await page.SelectAsync("select[class*='day'", $"{_data.BirthDate.Day}");194 await page.ClickAsync("select[class*='month'");195 await page.SelectAsync("select[class*='month'", $"{_data.BirthDate.Month}");196 await page.ClickAsync("select[class*='year'");197 await page.SelectAsync("select[class*='year'", $"{_data.BirthDate.Year}");198 return;199 }200 var eDay = await page.QuerySelectorAsync(".b-date__day span");201 if (eDay == null) eDay = await page.QuerySelectorAsync("div[data-test-id='birth-date__day']");202 await eDay.ClickAsync();203 var eDayClick = await page.QuerySelectorAsync($".day{_data.BirthDate.Day} > span");204 if (eDayClick == null) eDayClick = await page.QuerySelectorAsync($"div[data-test-id='select-value:{_data.BirthDate.Day}']");205 await eDayClick.ClickAsync();206 var eMonth = await page.QuerySelectorAsync(".b-date__month span");207 if (eMonth == null) eMonth = await page.QuerySelectorAsync("div[data-test-id='birth-date__month']");208 await eMonth.ClickAsync();209 var eMonthClick = await page.QuerySelectorAsync($".b-date__month a[data-num='{_data.BirthDate.Month - 1}'] > span");210 if (eMonthClick == null) eMonthClick = await page.QuerySelectorAsync($"div[data-test-id='select-value:{_data.BirthDate.Month}']");211 await eMonthClick.ClickAsync();212 var eYear = await page.QuerySelectorAsync(".b-date__year span");213 if (eYear == null) eYear = await page.QuerySelectorAsync("div[data-test-id='birth-date__year']");214 await eYear.ClickAsync();215 var eYearClick = await page.QuerySelectorAsync($".b-date__year a[data-value='{_data.BirthDate.Year}'] > span");216 if (eYearClick == null) eYearClick = await page.QuerySelectorAsync($"div[data-test-id='select-value:{_data.BirthDate.Year}']");217 await eYearClick.ClickAsync();218 }219 private async Task FillSex(Page page)220 {221 if (page.Url.Contains("light."))222 {223 switch (_data.Sex)224 {225 case SexCode.Male:226 await page.ClickAsync("input#man1");227 break;228 case SexCode.Female:229 await page.ClickAsync("input#man2");230 break;231 }232 return;233 }234 switch (_data.Sex)235 {236 case SexCode.Male:237 await page.ClickAsync("[value='male']");238 break;239 case SexCode.Female:240 await page.ClickAsync("[value='female']");241 break;242 }243 }244 private async Task FillEmail(Page page)245 {246 if (string.IsNullOrEmpty(_data.AccountName))247 {248 _data.AccountName = $"{_data.Firstname.ToLower()}.{_data.Lastname.ToLower()}";249 }250 //await page.TypeAsync("span.b-email__name>input[type='email']", _data.AccountName);251 var defaultDomain = ServiceDomains.GetDomain(ServiceCode.MailRu);252 if (string.IsNullOrEmpty(_data.Domain))253 {254 _data.Domain = ServiceDomains.GetDomain(ServiceCode.MailRu);255 }256 if (page.Url.Contains("light."))257 {258 if (!_data.Domain.ToLower().Equals(defaultDomain))259 {260 //select domain261 await page.ClickAsync("select[name='RegistrationDomain'");262 await page.SelectAsync("select[name='RegistrationDomain'", $"{_data.Domain.ToLower()}");263 }264 await page.ClickAsync("div#loginField input");265 await page.TypeAsync("div#loginField input", _data.AccountName, _typeOptions);266 return;267 }268 if (!_data.Domain.ToLower().Equals(defaultDomain))269 {270 //select domain271 await page.ClickAsync("span.b-email__domain span");272 await page.ClickAsync($"a[data-text='@{_data.Domain}']");273 }274 const string selAltMail = "div.b-tooltip_animate";275 //await page.WaitForTimeoutAsync(1000);276 //var altMailExists = await page.QuerySelectorAsync(selAltMail);277 var emailAlreadyRegistered = await EmailAlreadyRegistered(_data.AccountName, _data.Domain, page);278 //if (altMailExists != null)279 if (emailAlreadyRegistered)280 {281 var selAltMailList = $"{selAltMail} div.b-list__item__content";282 var eAltMailList = await page.QuerySelectorAsync(selAltMailList);283 if (eAltMailList == null)284 {285 selAltMailList = "[data-test-id=account-name-tooltip] a";286 eAltMailList = await page.QuerySelectorAsync(selAltMailList);287 }288 var altMailElements = await page.QuerySelectorAllAsync(selAltMailList);289 var jsAltMailList = $@"Array.from(document.querySelectorAll('{selAltMailList}')).map(a => a.innerText);";290 var altMailList = await page.EvaluateExpressionAsync<string[]>(jsAltMailList);291 var altEmail = altMailList.FirstOrDefault(z => z.Contains(_data.Domain));292 if (string.IsNullOrEmpty(altEmail)) altEmail = altMailList[0];293 _data.AccountName = altEmail.Split('@')[0];294 _data.Domain = altEmail.Split('@')[1];295 var idx = Array.IndexOf(altMailList, altEmail);296 //altMailElements = await page.QuerySelectorAllAsync(selAltMailList);297 if (altMailElements.Length > idx) await altMailElements[idx].ClickAsync();298 }299 }300 private async Task FillPassword(Page page)301 {302 if (page.Url.Contains("light."))303 {304 await page.TypeAsync("div[class*=pass] input[type='password']", _data.Password, _typeOptions);305 await page.TypeAsync("div[class*=passverify] input[type='password']", _data.Password, _typeOptions);306 return;307 }308 var ePassword = await page.QuerySelectorAsync("input[name='password']");309 if (ePassword == null) ePassword = await page.QuerySelectorAsync("input[data-test-id='password-input']");310 await ePassword.TypeAsync(_data.Password, _typeOptions);311 await page.WaitForTimeoutAsync(500);312 var ePasswordRetry = await page.QuerySelectorAsync("input[name='password_retry']");313 if (ePasswordRetry == null) ePasswordRetry = await page.QuerySelectorAsync("input[data-test-id='password-confirm-input']");314 await ePasswordRetry.TypeAsync(_data.Password, _typeOptions);315 await page.WaitForTimeoutAsync(500);316 }317 private async Task FillAdditionalEmail(Page page)318 {319 //email instead phonenumber320 var eLink = await page.QuerySelectorAsync("div.b-form-field__message>a");321 if (eLink == null) eLink = await page.QuerySelectorAsync("a[data-test-id='phone-number-switch-link']");322 await eLink.ClickAsync();323 await page.WaitForTimeoutAsync(500);324 var eInput = await page.QuerySelectorAsync("span.b-email__name input[name='additional_email']");325 if (eInput == null) eInput = await page.QuerySelectorAsync("input[data-test-id='extra-email']");326 //await page.WaitForTimeoutAsync(500);327 await eInput.TypeAsync("pvachovski@bk.ru");328 await page.WaitForTimeoutAsync(1500);329 await ClickSubmit(page);330 }331 private async Task FillPhone(Page page)332 {333 if (page.Url.Contains("light."))334 {335 await page.TypeAsync("input[name='RemindPhone']", _data.Phone, _typeOptions);336 return;337 }338 const string selPhone = "input[type=tel]";339 var elPhone = await page.QuerySelectorAsync(selPhone);340 if (elPhone != null && await elPhone.IsIntersectingViewportAsync())341 {342 await page.ClickAsync(selPhone);343 await page.EvaluateFunctionAsync("function() {" + $"document.querySelector('{selPhone}').value = ''" + "}");344 await page.TypeAsync(selPhone, _data.Phone, _typeOptions);345 await page.WaitForTimeoutAsync(1500);346 }347 //else348 //{349 // Log.Error("Phone input not found");350 //}351 }352 private static async Task ClickSubmit(Page page)353 {354 var elSignUp = await page.QuerySelectorAsync("div.b-form__control>button");355 if (elSignUp == null) elSignUp = await page.QuerySelectorAsync("button[type='submit']");356 if (elSignUp == null) elSignUp = await page.QuerySelectorAsync("button[data-test-id='first-step-submit']");357 if (elSignUp == null) elSignUp = await page.QuerySelectorAsync("button[data-name='submit']");358 if (elSignUp == null) elSignUp = await page.QuerySelectorAsync("button[data-test-id='verification-next-button'] ");359 await elSignUp.ClickAsync();360 await page.WaitForTimeoutAsync(1500);361 }362 private async Task SolveRecaptcha(Page page)363 {364 var eRecaptcha = await page.QuerySelectorAsync("#g-recaptcha-response");365 if (eRecaptcha != null)366 {367 var anticaptchaScriptText = File.ReadAllText(Path.GetFullPath(".\\Data\\init.js"));368 anticaptchaScriptText = anticaptchaScriptText.Replace("YOUR-ANTI-CAPTCHA-API-KEY", AntiCaptchaOnlineApi.GetApiKeyAnticaptcha());369 await page.EvaluateExpressionAsync(anticaptchaScriptText);370 anticaptchaScriptText = File.ReadAllText(Path.GetFullPath(".\\Data\\recaptchaaiMailRu.js"));371 await page.EvaluateExpressionAsync(anticaptchaScriptText);372 //await page.AddScriptTagAsync("https://cdn.antcpt.com/imacros_inclusion/recaptcha.js");373 //await page.WaitForSelectorAsync(".antigate_solver.solved", new WaitForSelectorOptions { Timeout = 120 * 1000 });374 await page.WaitForTimeoutAsync(90 * 1000);375 var eSubmit = await page.QuerySelectorAsync("button[data-test-id='verification-next-button'");376 eRecaptcha = await page.QuerySelectorAsync("#g-recaptcha-response");377 if (eSubmit != null && eRecaptcha != null) await eSubmit.ClickAsync();378 //await page.ClickAsync("input[type=submit]");379 //await page.WaitForNavigationAsync(new NavigationOptions { Timeout = 120 * 1000 });380 //await page.WaitForTimeoutAsync(60 * 1000);381 await SolveRecaptcha(page);382 }383 }384 #endregion385 #region else386 private async static Task SetHooks(Page page)387 {388 //await page.SetRequestInterceptionAsync(true);389 //page.Request += Page_Request;390 page.FrameNavigated += Page_FrameNavigated;391 }392 private async static void Page_FrameNavigated(object sender, FrameEventArgs e)393 {394 Log.Info($"{nameof(Page_FrameNavigated)} {e.Frame.Url}");...
FacebookRegistration.cs
Source:FacebookRegistration.cs
...65 //}66 public async Task RegistrateByPhone(Page page)67 {68 await FillRegistrationData(page);69 await page.WaitForTimeoutAsync(3000);70 await ClickSubmit(page);71 // check phone accepted72 try73 {74 await page.WaitForNavigationAsync();75 }76 catch (Exception exception)77 {78 Log.Debug(exception);79 await _smsService.SetNumberFail(_requestId);80 _data.ErrMsg = BotMessages.PhoneNumberNotAcceptMessage;81 return;82 }83 await page.WaitForTimeoutAsync(3000);84 var eVerify = await page.QuerySelectorAsync("#checkpointSubmitButton");85 if (eVerify != null) { 86 await eVerify.ClickAsync();87 try { await page.WaitForNavigationAsync(_navigationOptions); } catch { }88 //var pages = await page.Browser.PagesAsync();89 //page = pages[0];90 }91 //await SolveRecaptcha(page);92 await FillPhoneAgain(page);93 var phoneNumberValidation = await _smsService.GetSmsValidation(_requestId);94 Log.Info($"phoneNumberValidation: {JsonConvert.SerializeObject(phoneNumberValidation)}");95 if (phoneNumberValidation != null)96 {97 await _smsService.SetSmsValidationSuccess(_requestId);98 const string selSmsCode = "input#code_in_cliff";99 await page.ClickAsync(selSmsCode);100 await page.TypeAsync(selSmsCode, phoneNumberValidation.Code);101 await page.ClickAsync("div.uiInterstitialContent button");102 await page.WaitForSelectorAsync("div._t a", new WaitForSelectorOptions { Timeout = 20000 });103 await page.ClickAsync("div._t a");104 await page.WaitForNavigationAsync();105 await page.WaitForTimeoutAsync(3000);106 _data.Success = true;107 }108 else await _smsService.SetNumberFail(_requestId);109 }110 #region Steps111 private async Task FillRegistrationData(Page page)112 {113 var _typeOptions = new TypeOptions { Delay = 50 };114 var eSignUp = await page.QuerySelectorAsync("#signup-button");115 if (eSignUp != null) await eSignUp.ClickAsync();116 #region Name117 await page.WaitForSelectorAsync("input[name=firstname]", new WaitForSelectorOptions { Visible = true });118 await page.ClickAsync("input[name=firstname]");119 await page.TypeAsync("input[name=firstname]", _data.Firstname, _typeOptions);120 await page.TypeAsync("input[name=lastname]", _data.Lastname, _typeOptions);121 #endregion122 await page.TypeAsync("input[name=reg_email__]", _data.Phone, _typeOptions);123 await page.TypeAsync("input[name=reg_passwd__]", _data.Password, _typeOptions);124 await page.WaitForTimeoutAsync(500);125 await page.ClickAsync("select#day");126 await page.WaitForTimeoutAsync(500);127 await page.SelectAsync("select#day", $"{_data.BirthDate.Day}");128 await page.ClickAsync("select#month");129 await page.WaitForTimeoutAsync(500);130 await page.SelectAsync("select#month", $"{_data.BirthDate.Month}");131 await page.WaitForTimeoutAsync(500);132 await page.ClickAsync("select#year");133 await page.SelectAsync("select#year", $"{_data.BirthDate.Year}");134 if (_data.Sex == SexCode.Female) await page.ClickAsync("input[name=sex][value='1']");135 if (_data.Sex == SexCode.Male) await page.ClickAsync("input[name=sex][value='2']");136 }137 private async Task SolveRecaptcha(Page page, int deep = 0)138 {139 if (deep >= 2) return;140 var eGotoRecapthcha = await page.QuerySelectorAsync("#checkpointSubmitButton");141 if (eGotoRecapthcha == null) return;142 await eGotoRecapthcha.ClickAsync();143 await page.WaitForTimeoutAsync(2000);144 var eRecaptcha = await page.QuerySelectorAsync("#captcha_response");145 if (eRecaptcha != null)146 {147 //var targets = page.Browser.Targets();148 var anticaptchaScriptText = File.ReadAllText(Path.GetFullPath(".\\Data\\init.js"));149 anticaptchaScriptText = anticaptchaScriptText.Replace("YOUR-ANTI-CAPTCHA-API-KEY", AntiCaptchaOnlineApi.GetApiKeyAnticaptcha());150 await page.EvaluateExpressionAsync(anticaptchaScriptText);151 anticaptchaScriptText = File.ReadAllText(Path.GetFullPath(".\\Data\\recaptchaaifb.js"));152 await page.EvaluateExpressionAsync(anticaptchaScriptText);153 //targets[8].154 //await page.AddScriptTagAsync(new AddTagOptions { Content= anticaptchaScriptText });155 //await page.WaitForSelectorAsync(".antigate_solver.solved", new WaitForSelectorOptions { Timeout = 120 * 1000 });156 // await page.ClickAsync("input[type=submit]");157 //await page.WaitForNavigationAsync();158 try { await page.WaitForTimeoutAsync(90 * 1000); } catch { }159 await SolveRecaptcha(page, ++deep);160 }161 }162 private async Task ClickSubmit(Page page)163 {164 var elSignUp = await page.QuerySelectorAsync("button[type=submit]");165 await elSignUp.ClickAsync();166 await page.WaitForTimeoutAsync(500);167 }168 private async Task FillPhoneAgain(Page page)169 {170 var eSendCode = await page.QuerySelectorAsync("button[name='submit[set_contact_point_primary_button]']");171 if (eSendCode == null) return;172 var selCountries = "ul[role=menu] a>span>span";173 var eCountries = await page.QuerySelectorAllAsync(selCountries);174 if (eCountries == null) return;175 var jsAltMailList = $@"Array.from(document.querySelectorAll('{selCountries}')).map(a => a.innerText);";176 var countries = await page.EvaluateExpressionAsync<string[]>(jsAltMailList);177 // код ÑÑÑÐ°Ð½Ñ +44178 var country = countries.FirstOrDefault(z => z.Contains($"(+{_countryPrefix})"));179 var idx = Array.IndexOf(countries, country);180 if (eCountries.Length > idx) await eCountries[idx].ClickAsync();...
ClickerBot.cs
Source:ClickerBot.cs
...34 {35 Visible = true,36 Timeout = 500037 });38 await page.WaitForTimeoutAsync(1000);39 var pillButton = await page.QuerySelectorAsync(".btn.btn-primary.btn-pill.btn-lg");40 await pillButton.ClickAsync();41 }42 catch (System.Exception)43 {44 return ClickResult.Success; 45 }46 }47 else48 {49 await page.WaitForTimeoutAsync(1000);50 if (!await page.NavigateAndWait(followUpUrl))51 return ClickResult.NetworkIssue;52 }53 await page.WaitForSelectorAsync("iframe", new WaitForSelectorOptions54 {55 Visible = true,56 Timeout = 500057 });58 var iframe = await page.QuerySelectorAsync("iframe");59 var contentFrame = await iframe.ContentFrameAsync();60 var iterationsWithoutElement = 0;61 while (true)62 {63 ElementHandle elementToClick = null;64 while (elementToClick == null)65 {66 iterationsWithoutElement++;67 if (iterationsWithoutElement > 15)68 return ClickResult.NoButtonToClick;69 elementToClick = await GetNextElementToClick(contentFrame);70 }71 iterationsWithoutElement = 0;72 try73 {74 await elementToClick.ClickAsync();75 }76 catch (System.Exception e)77 {78 var x = 10;79 // we were slightly to fast, element just disappeared or did not appear completely (yet). 80 }81 }82 }83 catch (System.Exception e)84 {85 return ClickResult.UserAbort;86 }87 }88 private void ClearLog()89 {90 File.WriteAllText("log.txt", "");91 }92 private void Log(string toLog)93 {94 File.AppendAllLines("log.txt", new List<string>{ toLog });95 }96 /// <summary>97 /// Just some random element being returned from the page. Do not ask me about the order...98 /// </summary>99 /// <param name="frame"></param>100 /// <returns></returns>101 private async Task<ElementHandle> GetNextElementToClick(Frame frame)102 {103 var timeout = 1000;104 await frame.WaitForTimeoutAsync(timeout);105 await UpdateWrongQuizAnswers(frame);106 var highImportanceButtons = await frame.QuerySelectorAllAsync(".question-example-overlay:not([hidden='hidden']) .example-buttons .button:not(.is-disabled)");107 foreach (var buttonHandle in highImportanceButtons)108 {109 var boundingBox = await buttonHandle.BoundingBoxAsync();110 var isVisible = boundingBox != null && boundingBox.Width > 0 && boundingBox.Height > 0;111 if (!isVisible)112 continue;113 var buttonText = await frame.GetInnerText(buttonHandle);114 var isCandidate = new[] { "schlieÃen" }.Any(x => buttonText.ToLower().Contains(x));115 if (isCandidate)116 return buttonHandle;117 }118 var decisionTextHandle = await frame.QuerySelectorAllAsync(".decision-wrapper .text-column");...
Examples.cs
Source:Examples.cs
...70 await _page.WaitForExpressionAsync("1 + 1 === 2", new WaitForFunctionOptions { Timeout = timeout });71 await _page.WaitForFunctionAsync("() => window.location.href === 'https://github.com/hardkoded/puppeteer-sharp'", new WaitForFunctionOptions { Timeout = timeout });72 await _page.WaitForSelectorAsync("#readme", new WaitForSelectorOptions { Timeout = timeout });73 await _page.WaitForXPathAsync("//*[@id='readme']", new WaitForSelectorOptions { Timeout = timeout });74 await _page.WaitForTimeoutAsync(timeout);75 // WaitUntilNavigation76 new NavigationOptions().WaitUntil = new[]77 {78 WaitUntilNavigation.Load,79 WaitUntilNavigation.DOMContentLoaded,80 WaitUntilNavigation.Networkidle0,81 WaitUntilNavigation.Networkidle282 };83 // Frame84 var frame = _page.MainFrame;85 await frame.WaitForExpressionAsync("1 + 1 === 2", new WaitForFunctionOptions { Timeout = timeout });86 await frame.WaitForFunctionAsync("() => window.location.href === 'https://github.com/hardkoded/puppeteer-sharp'", new WaitForFunctionOptions { Timeout = timeout });87 await frame.WaitForSelectorAsync("#readme", new WaitForSelectorOptions { Timeout = timeout });88 await frame.WaitForXPathAsync("//*[@id='readme']", new WaitForSelectorOptions { Timeout = timeout });89 await frame.WaitForTimeoutAsync(timeout);90 }91 [Fact]92 public async Task values_from_Page()93 {94 var url = _page.Url;95 var title = await _page.GetTitleAsync();96 var content = await _page.GetContentAsync();97 var cookies = await _page.GetCookiesAsync();98 }99 [Fact]100 public async Task form()101 {102 await _page.GoToAsync("https://www.techlistic.com/p/selenium-practice-form.html");103 // input / text...
MailRuRegistration.Mail.cs
Source:MailRuRegistration.Mail.cs
...25 var eDomainValue = await page.QuerySelectorAsync($"a[data-text='@{host}']");26 if (eDomainValue == null) eDomainValue = await page.QuerySelectorAsync($"div[data-test-id='select-value:@{host}']");27 await eDomainValue.ClickAsync();28 }29 await page.WaitForTimeoutAsync(1000);30 var altMailExists = await page.QuerySelectorAsync("div.b-tooltip_animate");31 if (altMailExists == null) altMailExists = await page.QuerySelectorAsync("[data-test-id='exists']");32 return altMailExists != null;33 }34 public static async Task<bool> Login(string accountName, string password, Page page)35 {36 //page.EmulateAsync(DeviceDescriptors.Get(DeviceDescriptorName.IPhone6);37 try38 {39 await page.TypeAsync("input[name=Login]", accountName, _typeOptions);40 await page.WaitForTimeoutAsync(500);41 await ClickSubmit(page);42 await page.WaitForTimeoutAsync(500);43 await page.TypeAsync("input[name=Password]", password, _typeOptions);44 await ClickSubmit(page);45 var navigationOptions = new NavigationOptions { WaitUntil = new[] { WaitUntilNavigation.DOMContentLoaded } };46 await page.WaitForNavigationAsync(navigationOptions);47 }48 catch (Exception exception)49 {50 Log.Error(exception);51 return false;52 }53 return true;54 }55 public static async Task<bool> SendEmail(string to, string subject, string[] text, Page page)56 {57 try58 {59 await page.WaitForTimeoutAsync(2000);60 var selNewLetter = "span.compose-button>span>span";61 if (await page.QuerySelectorAsync(selNewLetter) == null) selNewLetter = "a[data-name=compose] span";62 await page.ClickAsync(selNewLetter);63 await page.WaitForTimeoutAsync(1500);64 var selTo = "div[data-type=to] input";65 if (await page.QuerySelectorAsync(selTo) == null) selTo = "div[data-blockid='compose_to']";66 await page.ClickAsync(selTo);67 await page.TypeAsync(selTo, to, _typeOptions);68 var selSubject = "input[name=Subject]";69 //await page.ClickAsync("label[data-for=Subject]") ;70 await page.TypeAsync(selSubject, subject, _typeOptions);71 var selText = "div[role=textbox] div div";72 if (await page.QuerySelectorAsync(selText) == null)73 {74 var elText = await page.QuerySelectorAsync("span.mceEditor iframe");75 var frame = await elText.ContentFrameAsync();76 var elBody = await frame.QuerySelectorAsync("body");77 await elBody.TypeAsync(string.Join(Environment.NewLine, text), _typeOptions);...
zhifubao.cs
Source:zhifubao.cs
...15 {16 //Request URL to get the page17 // await page.GoToAsync(runnerInfo.URL);18 await page.GoToAsync("https://consumeprod.alipay.com/record/advanced.htm");19 // await page.WaitForTimeoutAsync(10000);20 // var frame1 = page.Frames.First(f => f.Name == "frame1"); 21 // var frame2 = page.MainFrame;22 // var frame1 = frame2.ChildFrames.First(); 23 // var waitForXPathPromise = frame1.WaitForXPathAsync("//div");24 //var test=await frame1.GetContentAsync();25 var ifrmElement = await page.WaitForSelectorAsync("#J-datetime-select > a:nth-child(3)");26 // ifrmElement.27 //var ifrmFrame = await ifrmElement.ContentFrameAsync();28 //var ifrmHtml = await ifrmFrame.GetContentAsync();29 // var test = await page.SelectAsync("#J-datetime-select > a:nth-child(3)");30 await page.ClickAsync("#J-datetime-select > a:nth-child(3)");31 await page.ClickAsync("body > div:nth-child(19) > ul > li:nth-child(5)");32 // await ifrmElement.ClickAsync();33 var ifrmElement1 = await page.XPathAsync("/html/body/div[10]/ul/li[5]");...
FrameWaitForTimeoutTests.cs
Source:FrameWaitForTimeoutTests.cs
...17 public async Task WaitsForTheGivenTimeoutBeforeResolving()18 {19 await Page.GoToAsync(TestConstants.EmptyPage);20 var startTime = DateTime.Now;21 await Page.MainFrame.WaitForTimeoutAsync(1000);22 Assert.True((DateTime.Now - startTime).TotalMilliseconds > 700);23 Assert.True((DateTime.Now - startTime).TotalMilliseconds < 1300);24 }25 }26}...
WaitForTimeoutAsync
Using AI Code Generation
1using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true }))2{3 var page = await browser.NewPageAsync();4 await page.WaitForTimeoutAsync(5000);5}6using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true }))7{8 var page = await browser.NewPageAsync();9 await page.WaitForTimeoutAsync(5000);10}11using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true }))12{13 var page = await browser.NewPageAsync();14 await page.WaitForTimeoutAsync(5000);15}16using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true }))17{18 var page = await browser.NewPageAsync();19 await page.WaitForTimeoutAsync(5000);20}21using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true }))22{23 var page = await browser.NewPageAsync();24 await page.WaitForTimeoutAsync(5000);25}26using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true }))27{28 var page = await browser.NewPageAsync();29 await page.WaitForTimeoutAsync(5000);30}31using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true }))32{33 var page = await browser.NewPageAsync();
WaitForTimeoutAsync
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static void Main(string[] args)7 {8 MainAsync().GetAwaiter().GetResult();9 }10 static async Task MainAsync()11 {12 var options = new LaunchOptions { Headless = true };13 using (var browser = await Puppeteer.LaunchAsync(options))14 using (var page = await browser.NewPageAsync())15 {16 await page.WaitForTimeoutAsync(5000);17 await page.ScreenshotAsync("google.png");18 }19 }20 }21}22public Task WaitForFunctionAsync(string pageFunction, object[] args = null, WaitForFunctionOptions options = null, bool isFunction = false)23using System;24using System.Threading.Tasks;25using PuppeteerSharp;26{27 {28 static void Main(string[] args)29 {30 MainAsync().GetAwaiter().GetResult();31 }32 static async Task MainAsync()33 {34 var options = new LaunchOptions { Headless = true };35 using (var browser = await Puppeteer.LaunchAsync(options))36 using (var page = await browser.NewPageAsync())
WaitForTimeoutAsync
Using AI Code Generation
1using System.Threading.Tasks;2using PuppeteerSharp;3{4 {5 static async Task Main(string[] args)6 {7 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);8 var browser = await Puppeteer.LaunchAsync(new LaunchOptions9 {10 });11 var page = await browser.NewPageAsync();12 await page.WaitForTimeoutAsync(10000);13 await browser.CloseAsync();14 }15 }16}
WaitForTimeoutAsync
Using AI Code Generation
1var page = await browser.NewPageAsync();2var frame = page.MainFrame;3var response = await frame.WaitForTimeoutAsync(10000);4Console.WriteLine("WaitForTimeoutAsync method of PuppeteerSharp.Frame class is used to wait for 10 seconds");5Console.WriteLine("Response: "+response);6var page = await browser.NewPageAsync();7var response = await page.WaitForTimeoutAsync(10000);8Console.WriteLine("WaitForTimeoutAsync method of PuppeteerSharp.Page class is used to wait for 10 seconds");9Console.WriteLine("Response: "+response);10Recommended Posts: PuppeteerSharp | Page.WaitForTimeoutAsync() Method11PuppeteerSharp | Page.WaitForNavigationAsync() Method12PuppeteerSharp | Page.WaitForRequestAsync() Method13PuppeteerSharp | Page.WaitForResponseAsync() Method14PuppeteerSharp | Page.WaitForSelectorAsync() Method
WaitForTimeoutAsync
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4using CommandLine;5{6 {7 static async Task Main(string[] args)8 {9 var options = new LaunchOptions { Headless = true };10 using (var browser = await Puppeteer.LaunchAsync(options))11 {12 using (var page = await browser.NewPageAsync())13 {14 var frame = page.MainFrame;15 var timeout = 1000;16 var timeoutReached = await frame.WaitForTimeoutAsync(timeout);17 if (timeoutReached)18 {19 Console.WriteLine($"Timeout of {timeout} ms reached");20 }21 {22 Console.WriteLine($"Timeout of {timeout} ms not reached");23 }24 }25 }26 }27 }28}29using System;30using System.Threading.Tasks;31using PuppeteerSharp;32using CommandLine;33{34 {35 static async Task Main(string[] args)36 {37 var options = new LaunchOptions { Headless = true };38 using (var browser = await Puppeteer.LaunchAsync(options))39 {40 using (var page = await browser.NewPageAsync())41 {42 var frame = page.MainFrame;43 var timeout = 1000;44 var timeoutReached = await frame.WaitForTimeoutAsync(timeout);45 if (timeoutReached)46 {47 Console.WriteLine($"Timeout of {timeout} ms reached");48 }49 {50 Console.WriteLine($"Timeout of {timeout} ms not reached
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 LaunchOptions 10 { 11 });12 var page = await browser.NewPageAsync();13 var timeout = 5000;14 var timeoutTask = page.WaitForTimeoutAsync(timeout);15 await timeoutTask;16 await browser.CloseAsync();17 }18 }19}
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!!