How to use WaitForTimeoutAsync method of PuppeteerSharp.Frame class

Best Puppeteer-sharp code snippet using PuppeteerSharp.Frame.WaitForTimeoutAsync

Run Puppeteer-sharp automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

FacebookRegistration.cs

Source: FacebookRegistration.cs Github

copy
1using AnticaptchaOnline;
2using Common.Service;
3using Common.Service.Enums;
4using Common.Service.Interfaces;
5using log4net;
6using Newtonsoft.Json;
7using PuppeteerService;
8using PuppeteerSharp;
9using PuppeteerSharp.Input;
10using PuppeteerSharp.Mobile;
11using System;
12using System.IO;
13using System.Linq;
14using System.Threading.Tasks;
15
16namespace Facebook.Bot
17{
18    public class FacebookRegistration : RegistrationBot.Bot
19    {
20        #region init
21        #region fields
22        private static readonly ILog Log = LogManager.GetLogger(typeof(FacebookRegistration));
23        public const string RegistrationUrl = @"https://www.facebook.com/r.php"; //https://m.facebook.com/ https://www.facebook.com/
24        #endregion
25
26        public FacebookRegistration(IAccountData data, ISmsService smsService, IChromiumSettings chromiumSettings) : base(data, smsService, chromiumSettings)
27        {
28            var proxy = _chromiumSettings.GetProxy(ServiceCode.Facebook);
29            if (!string.IsNullOrEmpty(proxy)) _chromiumSettings.Proxy = proxy;
30        }
31
32        #region infra
33        protected override ServiceCode GetServiceCode() => ServiceCode.Facebook;
34
35        protected override async Task StartRegistration(Page page)
36        {
37            await page.GoToAsync(GetRegistrationUrl());
38            await RegistrateByPhone(page);
39        }
40
41        protected override string GetRegistrationUrl() => RegistrationUrl;
42
43        protected override DeviceDescriptorName GetDeviceDescriptorName()
44        {
45            return DeviceDescriptorName.IPhoneXLandscape;
46        }
47        #endregion 
48        #endregion
49
50        //public async Task<IAccountData> Registration(CountryCode countryCode)
51        //{
52        //    if (!string.IsNullOrEmpty(await SmsServiceInit(countryCode, ServiceCode.Facebook))) return _data;
53        //    using (var browser = await PuppeteerBrowser.GetBrowser(_chromiumSettings.GetPath(), _chromiumSettings.GetHeadless(), _chromiumSettings.GetArgs()))
54        //    {
55        //        try
56        //        {
57        //            using (var page = await PageInit(browser)) await RegistrateByPhone(page);
58        //            await _smsService.SetSmsValidationSuccess(_requestId);
59        //        }
60        //        catch (Exception exception)
61        //        {
62        //            Log.Error(exception);
63        //            if (string.IsNullOrEmpty(_data.ErrMsg)) _data.ErrMsg = exception.Message;
64        //            await _smsService.SetNumberFail(_requestId);
65        //        }
66        //        finally
67        //        {
68        //            await browser.CloseAsync();
69        //        }
70        //    }
71        //    return _data;
72        //}
73
74        public async Task RegistrateByPhone(Page page)
75        {
76
77            await FillRegistrationData(page);
78            await page.WaitForTimeoutAsync(3000);
79            await ClickSubmit(page);
80
81            // check phone accepted
82            try
83            {
84                await page.WaitForNavigationAsync();
85            }
86            catch (Exception exception)
87            {
88                Log.Debug(exception);
89                await _smsService.SetNumberFail(_requestId);
90                _data.ErrMsg = BotMessages.PhoneNumberNotAcceptMessage;
91                return;
92            }
93            await page.WaitForTimeoutAsync(3000);
94
95            var eVerify = await page.QuerySelectorAsync("#checkpointSubmitButton");
96            if (eVerify != null) { 
97                await eVerify.ClickAsync();
98                try { await page.WaitForNavigationAsync(_navigationOptions); } catch { }
99                //var pages = await page.Browser.PagesAsync();
100                //page = pages[0];
101            }
102            //await SolveRecaptcha(page);
103            await FillPhoneAgain(page);
104
105            var phoneNumberValidation = await _smsService.GetSmsValidation(_requestId);
106            Log.Info($"phoneNumberValidation: {JsonConvert.SerializeObject(phoneNumberValidation)}");
107            if (phoneNumberValidation != null)
108            {
109                await _smsService.SetSmsValidationSuccess(_requestId);
110                const string selSmsCode = "input#code_in_cliff";
111                await page.ClickAsync(selSmsCode);
112                await page.TypeAsync(selSmsCode, phoneNumberValidation.Code);
113                await page.ClickAsync("div.uiInterstitialContent button");
114                await page.WaitForSelectorAsync("div._t a", new WaitForSelectorOptions { Timeout = 20000 });
115                await page.ClickAsync("div._t a");
116
117                await page.WaitForNavigationAsync();
118                await page.WaitForTimeoutAsync(3000);
119                _data.Success = true;
120            }
121            else await _smsService.SetNumberFail(_requestId);
122
123        }
124
125        #region Steps
126        private async Task FillRegistrationData(Page page)
127        {
128            var _typeOptions = new TypeOptions { Delay = 50 };
129            var eSignUp = await page.QuerySelectorAsync("#signup-button");
130            if (eSignUp != null) await eSignUp.ClickAsync();
131
132
133            #region Name
134            await page.WaitForSelectorAsync("input[name=firstname]", new WaitForSelectorOptions { Visible = true });
135            await page.ClickAsync("input[name=firstname]");
136            await page.TypeAsync("input[name=firstname]", _data.Firstname, _typeOptions);
137            await page.TypeAsync("input[name=lastname]", _data.Lastname, _typeOptions);
138
139
140            #endregion
141
142            await page.TypeAsync("input[name=reg_email__]", _data.Phone, _typeOptions);
143            await page.TypeAsync("input[name=reg_passwd__]", _data.Password, _typeOptions);
144
145
146            await page.WaitForTimeoutAsync(500);
147            await page.ClickAsync("select#day");
148            await page.WaitForTimeoutAsync(500);
149            await page.SelectAsync("select#day", $"{_data.BirthDate.Day}");
150            await page.ClickAsync("select#month");
151            await page.WaitForTimeoutAsync(500);
152            await page.SelectAsync("select#month", $"{_data.BirthDate.Month}");
153            await page.WaitForTimeoutAsync(500);
154            await page.ClickAsync("select#year");
155            await page.SelectAsync("select#year", $"{_data.BirthDate.Year}");
156
157
158            if (_data.Sex == SexCode.Female) await page.ClickAsync("input[name=sex][value='1']");
159            if (_data.Sex == SexCode.Male) await page.ClickAsync("input[name=sex][value='2']");
160        }
161
162        private async Task SolveRecaptcha(Page page, int deep = 0)
163        {
164            if (deep >= 2) return;
165            var eGotoRecapthcha = await page.QuerySelectorAsync("#checkpointSubmitButton");
166            if (eGotoRecapthcha == null) return;
167            await eGotoRecapthcha.ClickAsync();
168            await page.WaitForTimeoutAsync(2000);
169            var eRecaptcha = await page.QuerySelectorAsync("#captcha_response");
170            if (eRecaptcha != null)
171            {
172                //var targets = page.Browser.Targets();
173                var anticaptchaScriptText = File.ReadAllText(Path.GetFullPath(".\\Data\\init.js"));
174                anticaptchaScriptText = anticaptchaScriptText.Replace("YOUR-ANTI-CAPTCHA-API-KEY", AntiCaptchaOnlineApi.GetApiKeyAnticaptcha());
175                await page.EvaluateExpressionAsync(anticaptchaScriptText);
176                anticaptchaScriptText = File.ReadAllText(Path.GetFullPath(".\\Data\\recaptchaaifb.js"));
177                await page.EvaluateExpressionAsync(anticaptchaScriptText);
178                //targets[8].
179
180                //await page.AddScriptTagAsync(new AddTagOptions { Content= anticaptchaScriptText });
181                //await page.WaitForSelectorAsync(".antigate_solver.solved", new WaitForSelectorOptions { Timeout = 120 * 1000 });
182                // await page.ClickAsync("input[type=submit]");
183                //await page.WaitForNavigationAsync();
184                try { await page.WaitForTimeoutAsync(90 * 1000); } catch { }
185                await SolveRecaptcha(page, ++deep);
186            }
187        }
188
189        private async Task ClickSubmit(Page page)
190        {
191            var elSignUp = await page.QuerySelectorAsync("button[type=submit]");
192            await elSignUp.ClickAsync();
193            await page.WaitForTimeoutAsync(500);
194        }
195
196        private async Task FillPhoneAgain(Page page)
197        {
198            var eSendCode = await page.QuerySelectorAsync("button[name='submit[set_contact_point_primary_button]']");
199            if (eSendCode == null) return;
200            var selCountries = "ul[role=menu] a>span>span";
201            var eCountries = await page.QuerySelectorAllAsync(selCountries);
202            if (eCountries == null) return;
203            var jsAltMailList = [email protected]"Array.from(document.querySelectorAll('{selCountries}')).map(a => a.innerText);";
204            var countries = await page.EvaluateExpressionAsync<string[]>(jsAltMailList);
205            // код страны +44
206            var country = countries.FirstOrDefault(z => z.Contains($"(+{_countryPrefix})"));
207            var idx = Array.IndexOf(countries, country);
208            if (eCountries.Length > idx) await eCountries[idx].ClickAsync();
209
210            var ePhone = await page.QuerySelectorAsync("input[type=tel]");
211            await ePhone.TypeAsync(_data.Phone.Replace($"+{_countryPrefix}", ""), _typeOptions);
212
213            await eSendCode.ClickAsync();
214        }
215        #endregion
216
217        #region else
218        private async static Task SetHooks(Page page)
219        {
220            //await page.SetRequestInterceptionAsync(true);
221
222            //page.Request += Page_Request;
223            //page.Response += Page_Response;
224
225            page.FrameAttached += Page_FrameAttached;
226            page.FrameNavigated += Page_FrameNavigated;
227
228            page.WorkerCreated += Page_WorkerCreated;
229        }
230
231        private static void Page_WorkerCreated(object sender, WorkerEventArgs e)
232        {
233            Log.Info($"{nameof(Page_WorkerCreated)} {e.Worker.Url}");
234        }
235
236        private async static void Page_FrameNavigated(object sender, FrameEventArgs e)
237        {
238            Log.Info($"{nameof(Page_FrameNavigated)} {e.Frame.Url}");
239            //if (e.Frame.Url.Contains("referer_frame"))
240            //{
241            //    var anticaptchaScriptText = File.ReadAllText(Path.GetFullPath(".\\Data\\recaptchaaifb.js"));
242            //    //await e.Frame.AddScriptTagAsync(new AddTagOptions { Url = "https://cdn.antcpt.com/imacros_inclusion/recaptcha.js" });
243            //    await e.Frame.AddScriptTagAsync(new AddTagOptions { Content = anticaptchaScriptText });
244            //}
245        }
246
247        private async static void Page_FrameAttached(object sender, FrameEventArgs e)
248        {
249            Log.Info($"{nameof(Page_FrameAttached)} {e.Frame.Url}");
250            //var anticaptchaScriptText = File.ReadAllText(Path.GetFullPath(".\\Data\\init.js"));
251            //anticaptchaScriptText = anticaptchaScriptText.Replace("YOUR-ANTI-CAPTCHA-API-KEY", AntiCaptchaOnlineApi.GetApiKeyAnticaptcha());
252            //await e.Frame.EvaluateExpressionAsync(anticaptchaScriptText);
253
254            //anticaptchaScriptText = File.ReadAllText(Path.GetFullPath(".\\Data\\recaptchaaifb.js"));
255            //await e.Frame.EvaluateExpressionAsync(anticaptchaScriptText);
256            //await e.Frame.AddScriptTagAsync(new AddTagOptions { Url = "https://cdn.antcpt.com/imacros_inclusion/recaptcha.js" });
257        }
258
259        private static async void Page_Response(object sender, ResponseCreatedEventArgs e)
260        {
261            Log.Info($"Page_Response {e.Response.Request.Url}");
262            if (e.Response.Request.Url.Contains("referer_frame"))
263            {
264                var body = await e.Response.TextAsync();
265                //await e.Response.Request.RespondAsync(new ResponseData { Body = body });
266            }
267
268        }
269
270        private static async void Page_Request(object sender, RequestEventArgs e)
271        {
272            //if (e.Request.Url.Contains("referer_frame"))
273            //{
274            //    //    //await e.Request.AbortAsync();
275            //    Log.Info(e.Request.Url);
276            //    await e.Request.ContinueAsync();
277            //    var body = await e.Request.Response.TextAsync();
278            //    await e.Request.RespondAsync(new ResponseData { Body = body });
279            //}
280            //else
281            //{
282            //    Log.Info(e.Request.Url);
283            //    await e.Request.ContinueAsync();
284            //}
285
286            await e.Request.ContinueAsync();
287            //var payload = new Payload()
288            //{
289            //    Url = "https://httpbin.org/forms/post",
290            //    Method = HttpMethod.Post /*,
291            //    PostData = keyValuePairs*/
292            //};
293            //await e.Request.ContinueAsync(payload);
294        } 
295        #endregion
296    }
297}
298
Full Screen

MailRuRegistration.Mail.cs

Source: MailRuRegistration.Mail.cs Github

copy
1using PuppeteerSharp;
2using System;
3using System.Threading.Tasks;
4
5namespace MailRu.Bot
6{
7    public partial class MailRuRegistration
8    {
9        public static string GetLoginUrl()
10        {
11            return @"https://account.mail.ru/login";
12        }
13
14        public static async Task<bool> EmailAlreadyRegistered(string accountName, string host, Page page)
15        {
16            var eAccountName = await page.QuerySelectorAsync("span.b-email__name>input[type='email']");
17            if (eAccountName == null) eAccountName = await page.QuerySelectorAsync("input[data-test-id='account__input']");
18            await eAccountName.TypeAsync(accountName);
19
20            const string defaultDomain = "mail.ru";
21            if (string.IsNullOrEmpty(host)) host = defaultDomain;
22
23            if (!host.ToLower().Equals(defaultDomain))
24            {
25                //select domain
26                var eDomain = await page.QuerySelectorAsync("span.b-email__domain span");
27                if (eDomain == null) eDomain = await page.QuerySelectorAsync("div[data-test-id='account__select']");
28                await eDomain.ClickAsync();
29                var eDomainValue = await page.QuerySelectorAsync($"a[data-text='@{host}']");
30                if (eDomainValue == null) eDomainValue = await page.QuerySelectorAsync($"div[data-test-id='select-value:@{host}']");
31                await eDomainValue.ClickAsync();
32            }
33
34            await page.WaitForTimeoutAsync(1000);
35            var altMailExists = await page.QuerySelectorAsync("div.b-tooltip_animate");
36            if (altMailExists == null) altMailExists = await page.QuerySelectorAsync("[data-test-id='exists']");
37            return altMailExists != null;
38        }
39
40        public static async Task<bool> Login(string accountName, string password, Page page)
41        {
42            //page.EmulateAsync(DeviceDescriptors.Get(DeviceDescriptorName.IPhone6);
43            try
44            {
45                await page.TypeAsync("input[name=Login]", accountName, _typeOptions);
46                await page.WaitForTimeoutAsync(500);
47                await ClickSubmit(page);
48                await page.WaitForTimeoutAsync(500);
49                await page.TypeAsync("input[name=Password]", password, _typeOptions);
50                await ClickSubmit(page);
51                var navigationOptions = new NavigationOptions { WaitUntil = new[] { WaitUntilNavigation.DOMContentLoaded } };
52                await page.WaitForNavigationAsync(navigationOptions);
53            }
54            catch (Exception exception)
55            {
56                Log.Error(exception);
57                return false;
58            }
59            return true;
60        }
61
62        public static async Task<bool> SendEmail(string to, string subject, string[] text, Page page)
63        {
64            try
65            {
66                await page.WaitForTimeoutAsync(2000);
67                var selNewLetter = "span.compose-button>span>span";
68                if (await page.QuerySelectorAsync(selNewLetter) == null) selNewLetter = "a[data-name=compose] span";
69                await page.ClickAsync(selNewLetter);
70                await page.WaitForTimeoutAsync(1500);
71                var selTo = "div[data-type=to] input";
72                if (await page.QuerySelectorAsync(selTo) == null) selTo = "div[data-blockid='compose_to']";
73                await page.ClickAsync(selTo);
74                await page.TypeAsync(selTo, to, _typeOptions);
75
76                var selSubject = "input[name=Subject]";
77                //await page.ClickAsync("label[data-for=Subject]") ;
78                await page.TypeAsync(selSubject, subject, _typeOptions);
79                var selText = "div[role=textbox] div div";
80                if (await page.QuerySelectorAsync(selText) == null)
81                {
82                    var elText = await page.QuerySelectorAsync("span.mceEditor iframe");
83                    var frame = await elText.ContentFrameAsync();
84                    var elBody = await frame.QuerySelectorAsync("body");
85                    await elBody.TypeAsync(string.Join(Environment.NewLine, text), _typeOptions);
86                }
87                else
88                {
89                    await page.ClickAsync(selText);
90                    await page.TypeAsync(selText, string.Join(Environment.NewLine, text), _typeOptions);
91                }
92                // or CTRL+ENTER 
93
94                var selSend = "span[data-title-shortcut='Ctrl+Enter']";
95                if (await page.QuerySelectorAsync(selSend) == null) selSend = "div[data-name=send]";
96                await page.ClickAsync(selSend);
97                await page.WaitForNavigationAsync(new NavigationOptions { Timeout = 5000 });
98
99            }
100            catch (Exception exception)
101            {
102                Log.Error(exception);
103                return false;
104            }
105            return true;
106        }
107    }
108}
109
Full Screen

FrameWaitForTimeoutTests.cs

Source: FrameWaitForTimeoutTests.cs Github

copy
1using System;
2using System.Threading.Tasks;
3using PuppeteerSharp.Tests.Attributes;
4using PuppeteerSharp.Xunit;
5using Xunit;
6using Xunit.Abstractions;
7
8namespace PuppeteerSharp.Tests.WaitForTests
9{
10    [Collection(TestConstants.TestFixtureCollectionName)]
11    public class FrameWaitForTimeoutTests : PuppeteerPageBaseTest
12    {
13        public FrameWaitForTimeoutTests(ITestOutputHelper output) : base(output)
14        {
15        }
16
17        [PuppeteerTest("waittask.spec.ts", "Frame.waitForTimeout", "waits for the given timeout before resolving")]
18        [PuppeteerFact]
19        public async Task WaitsForTheGivenTimeoutBeforeResolving()
20        {
21            await Page.GoToAsync(TestConstants.EmptyPage);
22            var startTime = DateTime.Now;
23            await Page.MainFrame.WaitForTimeoutAsync(1000);
24            Assert.True((DateTime.Now - startTime).TotalMilliseconds > 700);
25            Assert.True((DateTime.Now - startTime).TotalMilliseconds < 1300);
26        }
27    }
28}
29
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)