Best Puppeteer-sharp code snippet using PuppeteerSharp.Frame.TypeAsync
Methods.cs
Source:Methods.cs
...30 {31 data.Logger.LogHeader();32 var frame = GetFrame(data);33 var elem = (await frame.QuerySelectorAllAsync(BuildSelector(findBy, identifier)))[index];34 await elem.TypeAsync(text, new PuppeteerSharp.Input.TypeOptions { Delay = timeBetweenKeystrokes });35 data.Logger.Log($"Typed {text}", LogColors.DarkSalmon);36 }37 [Block("Types text in an input field with human-like random delays", name = "Type Human")]38 public static async Task PuppeteerTypeElementHuman(BotData data, FindElementBy findBy, string identifier, int index,39 string text)40 {41 data.Logger.LogHeader();42 var frame = GetFrame(data);43 var elem = (await frame.QuerySelectorAllAsync(BuildSelector(findBy, identifier)))[index];44 foreach (var c in text)45 {46 await elem.TypeAsync(c.ToString());47 await Task.Delay(data.Random.Next(100, 300)); // Wait between 100 and 300 ms (average human type speed is 60 WPM ~ 360 CPM)48 }49 data.Logger.Log($"Typed {text}", LogColors.DarkSalmon);50 }51 [Block("Clicks an element", name = "Click")]52 public static async Task PuppeteerClick(BotData data, FindElementBy findBy, string identifier, int index,53 PuppeteerSharp.Input.MouseButton mouseButton = PuppeteerSharp.Input.MouseButton.Left, int clickCount = 1,54 int timeBetweenClicks = 0)55 {56 data.Logger.LogHeader();57 var frame = GetFrame(data);58 var elem = (await frame.QuerySelectorAllAsync(BuildSelector(findBy, identifier)))[index];59 await elem.ClickAsync(new PuppeteerSharp.Input.ClickOptions { Button = mouseButton, ClickCount = clickCount, Delay = timeBetweenClicks });60 data.Logger.Log($"Clicked {clickCount} time(s) with {mouseButton} button", LogColors.DarkSalmon);...
PuppeteerMethods.cs
Source:PuppeteerMethods.cs
...143 WaitUntilNavigation[] waitUntil = new[] { WaitUntilNavigation.Networkidle0, WaitUntilNavigation.Networkidle2, WaitUntilNavigation.DOMContentLoaded, WaitUntilNavigation.Load };144 await page.GoToAsync("https://tr-tr.facebook.com/", new NavigationOptions { WaitUntil = waitUntil });145 await page.WaitForSelectorAsync("input#email");146 //You must change your facebook login informations.147 await page.TypeAsync("input#email", username);148 await page.TypeAsync("input#pass", password);149 await page.ClickAsync("button[name='login']");150 await page.WaitForNavigationAsync();151 var HtmlContent = await page.GetContentAsync();152 var Cookie = await page.GetCookiesAsync();153 var TitleOfPage = await page.GetTitleAsync();154 var filePath = "D:\\PdfFiles";155 var fileName = Guid.NewGuid() + ".pdf";156 if (!Directory.Exists(filePath))157 Directory.CreateDirectory(filePath);158 await page.PdfAsync(Path.Combine(filePath, fileName));159 return new SuccessPuppeteerResult("Pdf Created Succesfully");160 }161 catch (Exception ex)162 {163 return new ErrorPuppeteerResult("Error Occured! Detail: " + ex.Message);164 }165 finally166 {167 CloseChromium(page);168 }169 }170 }171 public static async Task<List<string>> VideoLinkList(Page page)172 {173 WaitUntilNavigation[] waitUntil = new[] { WaitUntilNavigation.Networkidle0, WaitUntilNavigation.Networkidle2, WaitUntilNavigation.DOMContentLoaded, WaitUntilNavigation.Load }; 174 var next = @"document.getElementById('pnnext')";175 var nexts = await page.EvaluateExpressionAsync<object>(next);176 var linkList = new List<string>();177 var isLastPage = (nexts == null);178 while ((nexts != null) || !isLastPage)179 {180 var jsSelectAllAnchors = @"Array.from(document.querySelectorAll('.g'))";181 var urls = await page.EvaluateExpressionAsync<object[]>(jsSelectAllAnchors);182 for (int i = 0; i < urls.Length; i++)183 {184 var query = $"document.querySelectorAll('.g')[{i}].getElementsByTagName('a')[0].href";185 linkList.Add(await page.EvaluateExpressionAsync<string>(query));186 }187 nexts = await page.EvaluateExpressionAsync<object>(next);188 if (nexts != null)189 {190 var nextHref = @"document.getElementById('pnnext').href";191 var nextHrefUrl = await page.EvaluateExpressionAsync<string>(nextHref);192 isLastPage = (nexts == null) && !string.IsNullOrEmpty(nextHrefUrl);193 await page.GoToAsync(nextHrefUrl, new NavigationOptions { WaitUntil = waitUntil });194 nexts = await page.EvaluateExpressionAsync<object>(next);195 }196 else197 {198 isLastPage = true;199 }200 }201 return linkList;202 } 203 public static async Task<PuppeteerDataResult<List<string>>> GetVideoSearchVideoResultUrlList(string url, string searchWord)204 {205 using (var page = await OpenChromiumPage())206 {207 WaitUntilNavigation[] waitUntil = new[] { WaitUntilNavigation.Networkidle0, WaitUntilNavigation.Networkidle2, WaitUntilNavigation.DOMContentLoaded, WaitUntilNavigation.Load };208 await page.GoToAsync(url, new NavigationOptions { WaitUntil = waitUntil });209 await SearchOnGoogle(searchWord, page);210 //Click Video Tab211 var videoTabElement = @"document.getElementsByClassName('hdtb-mitem')[4].getElementsByTagName('a')[0].href";212 var videoTabLink = await page.EvaluateExpressionAsync<string>(videoTabElement); 213 await page.GoToAsync(videoTabLink, new NavigationOptions { WaitUntil = waitUntil });214 215 var result= await VideoLinkList(page); 216 return new SuccessPuppeteerDataResult<List<string>>(result, "Get Title Successfully"); 217 }218 }219 public static async Task<PuppeteerDataResult<string>> GetSearchStaticticDetail(string url, string searchWord)220 {221 using (var page = await OpenChromiumPage())222 {223 WaitUntilNavigation[] waitUntil = new[] { WaitUntilNavigation.Networkidle0, WaitUntilNavigation.Networkidle2, WaitUntilNavigation.DOMContentLoaded, WaitUntilNavigation.Load };224 await page.GoToAsync(url, new NavigationOptions { WaitUntil = waitUntil });225 await SearchOnGoogle(searchWord, page);226 var jsExpression = @"document.querySelectorAll('#result-stats')[0].innerHTML";227 var result = await page.EvaluateExpressionAsync<string>(jsExpression);228 return new SuccessPuppeteerDataResult<string>(result, "");229 }230 }231 private static async Task SearchOnGoogle(string searchWord, Page page)232 {233 WaitUntilNavigation[] waitUntil = new[] { WaitUntilNavigation.Networkidle0, WaitUntilNavigation.Networkidle2, WaitUntilNavigation.DOMContentLoaded, WaitUntilNavigation.Load };234 //Search Text Input235 await page.WaitForSelectorAsync("input[name='q']");236 await page.TypeAsync("input[name='q']", searchWord);237 //Search on Google Button and Click Operation238 await page.WaitForSelectorAsync("input[name='btnK']");239 await page.EvaluateExpressionAsync("document.querySelector(\"input[name='btnK']\").click()");240 await page.WaitForNavigationAsync(new NavigationOptions { WaitUntil = waitUntil });241 }242 }243}...
Authorization.cs
Source:Authorization.cs
...69 Log.Information($"DefaultNavigationTimeout: {p.DefaultNavigationTimeout}");70 // ÐвÑоÑизаÑиÑ71 await p.WaitForSelectorAsync("#mobileOrEmail", WaitForSelectorTimeout);72 await p.FocusAsync("#mobileOrEmail");73 await p.Keyboard.TypeAsync(ConfigJson.Login);74 Log.Information($"Login: {timer.ElapsedMilliseconds}");75 timer.Restart();76 await p.WaitForSelectorAsync("#password", WaitForSelectorTimeout);77 await p.FocusAsync("#password");78 await p.Keyboard.TypeAsync(ConfigJson.Password);79 Log.Information($"Password: {timer.ElapsedMilliseconds}");80 timer.Restart();81 await p.WaitForSelectorAsync("#loginByPwdButton > span", WaitForSelectorTimeout);82 await p.ClickAsync("#loginByPwdButton > span");83 Log.Information($"ClickAuthorizationButton: {timer.ElapsedMilliseconds}");84 Log.Information("ÐвÑоÑизаÑиÑ: ÑÑпеÑно!");85 timer.Stop();86 /* ÐÑки нÑÐ¶Ð½Ñ Ð´Ð»Ñ Ñого, ÑÑÐ¾Ð±Ñ ÑÐ°Ð¹Ñ Ð¼ÐµÐ½Ñ Ð¾Ð¿Ð¾Ð·Ð½Ð°Ð»87 * пÑи оÑпÑавке http-запÑоÑа на ÑеÑÐ²ÐµÑ Ñл. дневника */88 // 10 попÑÑок полÑÑÐµÐ½Ð¸Ñ cookie.89 Cookie cookie;90 int count = 0;91 int attempts = (DefaultTimeout / 1000);92 do...
Robot.cs
Source:Robot.cs
...86 _ = await page.GoToAsync("https://i.qq.com");87 88 var loginFrame = await page.WaitForFrameAsync("login_frame");89 await (await loginFrame.WaitForSelectorAsync("#switcher_plogin")).ClickAsync();90 await (await loginFrame.WaitForSelectorAsync("#u")).TypeAsync(Account.Username);91 await (await loginFrame.WaitForSelectorAsync("#p")).TypeAsync(Account.Password);92 await (await loginFrame.WaitForSelectorAsync("#login_button")).ClickAsync();93 _ = await page.WaitForNavigationAsync();94 }95 private async Task UploadImage()96 {97 OnMessage("ç¹å»ç¸å");98 await (await page.WaitForSelectorAsync("a[title=\"ç¸å\"]")).ClickAsync();99 var tphotoFrame = await page.WaitForFrameAsync("tphoto", "app_canvas_frame");100 OnMessage("æå¼ä¸ä¼ 对è¯æ¡");101 await (await tphotoFrame.WaitForSelectorAsync(".j-uploadentry-photo")).ClickAsync();102 var uploadFrame = await page.WaitForFrameAsync("photoUploadDialog");103 await Delay();104 var imagePath = MainViewModel.RandomImage;105 OnMessage($"éæ©éæºæ件 {imagePath}");106 var fileChooserTask = page.WaitForFileChooserAsync();107 await Task.WhenAll(fileChooserTask, uploadFrame.ClickAsync(".btn-select-img"));108 await fileChooserTask.Result.AcceptAsync(imagePath.Replace(@"\", @"\\"));109 OnMessage("ä¸ä¼ æ件");110 await (await uploadFrame.WaitForSelectorAsync(".op-btn.btn-upload")).ClickAsync();111 _ = await page.WaitForSelectorAsync("#photoUploadDialog", new WaitForSelectorOptions() { Hidden = true });112 _ = await tphotoFrame.WaitForSelectorAsync("#desc_all");113 await Delay();114 OnMessage("å¡«åéæºææ¬");115 await tphotoFrame.TypeAsync("#desc_all", MainViewModel.RandomText);116 await Delay();117 await (await tphotoFrame.WaitForSelectorAsync("#back_btn_md")).ClickAsync();118 _ = await tphotoFrame.WaitForNavigationAsync();119 }120 private Task Delay()121 {122 var sec = (int)MainViewModel.DelaySec;123 var ms = sec * 1000;124 OnMessage($"延æ¶{sec}s");125 return Task.Delay(ms);126 }127 }128}...
Clean163Email.cs
Source:Clean163Email.cs
...20 var frame = page.Frames.First(s=>s.Name.Contains("x-URS-iframe"));21 22 //çå¾
æå·¥æä½23 var user = await frame.WaitForSelectorAsync("input[data-placeholder='é®ç®±å¸å·æææºå·ç ']");24 await user.TypeAsync("");25 var password = await frame.WaitForSelectorAsync("input[data-placeholder='è¾å
¥å¯ç ']");26 await password.TypeAsync("");27 await frame.ClickAsync("#dologin");28 var element = await page.WaitForXPathAsync("//*[a='æ¸
çé®ç®±']");29 var cleanBtn = await element.XPathAsync("a[1]");30 await cleanBtn[0].ClickAsync();31 await Task.Delay(3000);32 var frame2 = page.Frames.First(s => s.Name.Contains("frmoutlink"));33 34 await frame2.ClickAsync("#clearTypeDate");35 36 await frame2.ClickAsync("#dateCleanCustom");37 38 await frame2.TypeAsync("#customYearStartIpt", "1990");39 await frame2.TypeAsync("#customMonthStartIpt", "1");40 await frame2.TypeAsync("#customDayStartIpt", "1");41 await frame2.TypeAsync("#customYearEndIpt", "2021");42 await frame2.TypeAsync("#customMonthEndIpt", "2");43 await frame2.TypeAsync("#customDayEndIpt", "18");44 var wait = new WaitForSelectorOptions {Timeout = 5000};45 for (int i = 0; i < 100000; i++)46 {47 try48 {49 var b1 = await frame2.WaitForXPathAsync("//*/div[span='å¼å§æ«æ']", wait);50 await b1.ClickAsync();51 await Task.Delay(5000);52 var deleteBtn = await frame2.WaitForXPathAsync("//div[span='å½»åºå é¤']", wait);53 await deleteBtn.ClickAsync();54 var confirmBtn = await page.WaitForXPathAsync("//div[span='ç¡® å®']", wait);55 await confirmBtn.ClickAsync();56 await Task.Delay(4000);57 var confirm2Btn = await page.WaitForXPathAsync("//div[span='ç¡® å®']", wait);...
AuthIntegrationTests.cs
Source:AuthIntegrationTests.cs
...36 var page = await browser.NewPageAsync();37 await page.GoToAsync($"{app.RootUri}signup");38 {39 var emailField = await page.MainFrame.QuerySelectorAsync("#Email");40 await emailField.TypeAsync(Email);41 var passwordField = await page.MainFrame.QuerySelectorAsync("#Password");42 await passwordField.TypeAsync(Password);43 var confirmPasswordField = await page.MainFrame.QuerySelectorAsync("#ConfirmPassword");44 await confirmPasswordField.TypeAsync(Password);45 var submitButton = await page.MainFrame.QuerySelectorAsync("input[type=submit]");46 await submitButton.ClickAsync();47 await page.MainFrame.WaitForNavigationAsync();48 }49 {50 using var scope = app.Services.CreateScope();51 var dbContext = scope.ServiceProvider.GetRequiredService<DatabaseContext>();52 var query = from user in dbContext.Users.AsQueryable() where user.Email == Email select user;53 var exists = await query.AnyAsync();54 exists.Should().Be(true);55 }56 {57 var cookies = await page.GetCookiesAsync();58 await page.DeleteCookieAsync(cookies);59 await page.GoToAsync($"{app.RootUri}login", waitUntil: WaitUntilNavigation.DOMContentLoaded);60 }61 {62 var emailField = await page.MainFrame.QuerySelectorAsync("#Email");63 await emailField.TypeAsync(Email);64 var passwordField = await page.MainFrame.QuerySelectorAsync("#Password");65 await passwordField.TypeAsync(Password);66 var submitButton = await page.MainFrame.QuerySelectorAsync("input[type=submit]");67 await submitButton.ClickAsync();68 await page.MainFrame.WaitForNavigationAsync();69 var url = new Uri(page.Url);70 url.AbsolutePath.Should().Be("/");71 }72 }73 }74}...
KeyboardTypeFunction.cs
Source:KeyboardTypeFunction.cs
...47 {48 var element = await page.QuerySelectorByXPath(selector);49 if (element != null)50 {51 await element.TypeAsync(text, typeOptions);52 }53 else54 {55 throw new Exception($"Node not found with '{selector}' selector on type function");56 }57 }58 else59 {60 await page.TypeAsync(selector, text, typeOptions); 61 }62 }63 else64 {65 var currentFrame = page.Frames.FirstOrDefault(x => x.Name == frame);66 if (currentFrame != null)67 {68 if (selector.StartsWith(XPathSelector.XPathSelectorToken))69 {70 var element = await currentFrame.QuerySelectorByXPath(selector);71 if (element != null)72 {73 await element.TypeAsync(text, typeOptions);74 }75 else76 {77 throw new Exception($"Node not found with '{selector}' selector on type function");78 }79 }80 else81 {82 await currentFrame.TypeAsync(selector, text, typeOptions); 83 }84 }85 else86 {87 throw new Exception($"Frame not found with name '{frame}'");88 }89 }90 }91 #endregion92 }93}...
PuppeteerExtensions.cs
Source:PuppeteerExtensions.cs
...14 {15 ["Proxy-Authorization"] = authStr16 });17 }18 public static async Task TypeAsync(this Frame frame, string selector, string text)19 {20 await (await frame.QuerySelectorAsync(selector)).TypeAsync(text);21 }22 public static async Task ClickAsync(this Frame frame, string selector)23 {24 await (await frame.QuerySelectorAsync(selector)).ClickAsync();25 }26 public static async Task WaitForTruth(this Page page, string script, WaitForFunctionOptions opts = null)27 {28 var jsHandle = await page.WaitForExpressionAsync(script, opts);29 await jsHandle.DisposeAsync();30 }31 public static async Task WaitForDocumentInteractiveState(this Page page, int? timeout = null)32 {33 await page.WaitForTruth("document.readyState === 'interactive' || document.readyState === 'complete'", new WaitForFunctionOptions { Timeout = timeout ?? page.Browser.DefaultWaitForTimeout });34 }...
TypeAsync
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 { Headless = false });10 var page = await browser.NewPageAsync();11 var frame = page.MainFrame;12 var element = await frame.TypeAsync("input[name=q]", "puppeteer-sharp", new TypeOptions { Delay = 100 });13 await Task.Delay(5000);14 await browser.CloseAsync();15 }16 }17}
TypeAsync
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 {15 var page = await browser.NewPageAsync();16 await page.TypeAsync("input[name=q]", "PuppeteerSharp");17 await page.ClickAsync("input[name=btnK]");18 }19 }20 }21}
TypeAsync
Using AI Code Generation
1using System;2using System.Threading.Tasks;3{4 {5 static async Task Main(string[] args)6 {7 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);8 var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false });9 var page = await browser.NewPageAsync();10 await page.TypeAsync("input[title='Search']", "PuppeteerSharp");11 await page.ClickAsync("input[value='Google Search']");12 Console.ReadLine();13 }14 }15}16public async Task ClickAsync(string selector, ClickOptions options = null)17using System;18using System.Threading.Tasks;19{20 {21 static async Task Main(string[] args)22 {23 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);24 var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false });25 var page = await browser.NewPageAsync();26 await page.TypeAsync("input[title='Search']", "PuppeteerSharp");27 await page.ClickAsync("input[value='Google Search']");28 Console.ReadLine();29 }30 }31}32public async Task<ScreenshotData> ScreenshotAsync(ScreenshotOptions options = null)
TypeAsync
Using AI Code Generation
1var frame = page.Frames[0];2var type = frame.TypeAsync;3await type("#lst-ib", "PuppeteerSharp");4await page.ClickAsync("#tsbb");5var title = await page.GetTitleAsync();6Assert.Equal("PuppeteerSharp - Google Search", title);7await browser.CloseAsync();
TypeAsync
Using AI Code Generation
1var frame = page.MainFrame;2var result = await frame.TypeAsync("input[title=\"Search\"]", "Hello world");3Console.WriteLine(result);4Console.WriteLine("Hello World!");5Console.ReadLine();6var frame = page.MainFrame;7var result = await frame.TypeAsync("input[title=\"Search\"]", "Hello world", new TypeOptions { Delay = 100 });8Console.WriteLine(result);9Console.WriteLine("Hello World!");10Console.ReadLine();11var frame = page.MainFrame;12var result = await frame.TypeAsync("input[title=\"Search\"]", "Hello world", new TypeOptions { Delay = 100, NoWaitAfter = true });13Console.WriteLine(result);14Console.WriteLine("Hello World!");15Console.ReadLine();16var frame = page.MainFrame;17var result = await frame.TypeAsync("input[title=\"Search\"]", "Hello world", new TypeOptions { Delay = 100, NoWaitAfter = true, Timeout = 10000 });18Console.WriteLine(result);19Console.WriteLine("Hello World!");20Console.ReadLine();
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!!