Best Puppeteer-sharp code snippet using PuppeteerSharp.Page.FocusAsync
WebScraper.cs
Source:WebScraper.cs
...246 /// </summary>247 /// <param name="target">Javascript selector to make have focus.</param>248 public void Focus(string target)249 {250 FocusAsync(target).Wait();251 }252 private async Task FocusAsync(string target)253 {254 await m_page.FocusAsync(target);255 }256 /// <summary>257 /// Clicks on target element on page.258 /// </summary>259 /// <param name="target">Javascript selector of element to click on.</param>260 public void Click(string target)261 {262 ClickAsync(target).Wait();263 }264 private async Task ClickAsync(string target)265 {266 await m_page.ClickAsync(target);267 }268 /// <summary>...
Authorization.cs
Source:Authorization.cs
...68 Log.Information($"DefaultTimeout: {p.DefaultTimeout}");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);...
Program.cs
Source:Program.cs
...74 await ClickHyperlinkWithText(page, "A Generic RESTful CRUD HttpClient");75 }76 private static async Task TypeFieldValue(Page page, string fieldSelector, string value, int delay = 0)77 {78 await page.FocusAsync(fieldSelector);79 await page.TypeAsync(fieldSelector, value, new TypeOptions { Delay = delay });80 await page.Keyboard.PressAsync("Tab");81 }82 private static async Task SetDropdownValue(Page page, string dropdownId, string value)83 {84 var elementHandles = await page.XPathAsync($"//*[@id = \"{dropdownId}\"]/option[text() = \"{value}\"]");85 if (elementHandles.Length > 0)86 {87 var chosenOption = elementHandles[0];88 var jsHandle = await chosenOption.GetPropertyAsync("value");89 var choseOptionValue = await jsHandle.JsonValueAsync<string>();90 await page.FocusAsync($"#{dropdownId}");91 await page.SelectAsync($"#{dropdownId}", choseOptionValue);92 }93 else94 {95 await page.FocusAsync($"#{dropdownId}");96 await page.SelectAsync($"#{dropdownId}", value);97 }98 await page.Keyboard.PressAsync("Tab");99 }100 private static async Task ClickHyperlinkWithText(Page page, string hyperlinkText)101 { 102 var aElementsWithRestful = await page.XPathAsync($"//a[contains(text(), '{hyperlinkText}')]");103 if (aElementsWithRestful.Length == 1)104 {105 var navigationTask = page.WaitForNavigationAsync(_navigationOptions);106 var clickTask = aElementsWithRestful[0].ClickAsync();107 await Task.WhenAll(navigationTask, clickTask);108 }109 else...
TimeTrackingController.cs
Source:TimeTrackingController.cs
...47 48 await page.ClickAsync("#ctl00_ContentPlaceHolder_TiempoTextBox");49 await page.TypeAsync("#ctl00_ContentPlaceHolder_TiempoTextBox", tracking.Hours.ToString(), new TypeOptions{ Delay = 30 });50 await page.ClickAsync("#ctl00_ContentPlaceHolder_idTipoAsignacionDropDownList");51 //await page.FocusAsync("#ctl00_ContentPlaceHolder_idTipoAsignacionDropDownList");52 //await page.SelectAsync("#ctl00_ContentPlaceHolder_idTipoAsignacionDropDownList", tracking.AssignmentType);53 await page.ClickAsync("#ctl00_ContentPlaceHolder_DescripcionTextBox");54 await page.TypeAsync("#ctl00_ContentPlaceHolder_DescripcionTextBox", tracking.Description, new TypeOptions{ Delay = 30 });55 await page.FocusAsync("#ctl00_ContentPlaceHolder_idFocalPointClientDropDownList");56 await page.SelectAsync("#ctl00_ContentPlaceHolder_idFocalPointClientDropDownList", tracking.FocalPoint);57 await browser.CloseAsync();58 }).ConfigureAwait(false);59 }60 }61 62 public class Tracking63 {64 public string User { get; set; }65 66 public string Password { get; set; }67 68 public string Date { get; set; }69 ...
ShakespeareTranslationService.cs
Source:ShakespeareTranslationService.cs
...41 await page.EvaluateExpressionAsync("$('#english-text').val('')");42 await page.EvaluateExpressionAsync("$('#ghetto-text').val('')");43 // Set text44 //await page.EvaluateExpressionAsync($"$('#english-text').val('{text}')");45 await page.FocusAsync("#english-text");46 await page.Keyboard.TypeAsync(text, new TypeOptions() { Delay = 10 }); ;47 // Read translated text until we have same read twice48 // This is used with the purpose of waiting the correct text to be displayed49 // Could be achievied checking for the gif load animation status but we go with this solution50 // for semplicity51 string[] readAttempt = { string.Empty, string.Empty };52 int index = 0;53 var translatedTextSelector = @"document.querySelector('#ghetto-text').value;";54 while (true)55 {56 // Wait 1 sec57 await Task.Delay(1000);58 readAttempt[index % 2] = await page.EvaluateExpressionAsync<string>(translatedTextSelector);59 index++;...
AuthService.cs
Source:AuthService.cs
...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 }...
FocusFunction.cs
Source:FocusFunction.cs
...35 {36 var element = await page.QuerySelectorByXPath(selector);37 if (element != null)38 {39 await element.FocusAsync();40 }41 else42 {43 throw new Exception($"Node not found with '{selector}' selector on focus function");44 }45 }46 else47 {48 await page.FocusAsync(selector); 49 }50 }51 else52 {53 var currentFrame = page.Frames.FirstOrDefault(x => x.Name == frame);54 if (currentFrame != null)55 {56 if (selector.StartsWith(XPathSelector.XPathSelectorToken))57 {58 var element = await currentFrame.QuerySelectorByXPath(selector);59 if (element != null)60 {61 await element.FocusAsync();62 }63 else64 {65 throw new Exception($"Node not found with '{selector}' selector on focus function");66 }67 }68 else69 {70 await currentFrame.FocusAsync(selector); 71 }72 }73 else74 {75 throw new Exception($"Frame not found with name '{frame}'");76 }77 }78 }79 #endregion80 }81}...
PageExtensions.cs
Source:PageExtensions.cs
...9 {10 public static async Task TypeInputAsync(this Page page, string selector, string text)11 {12 await page.WaitForSelectorAsync(selector);13 await page.FocusAsync(selector);14 await page.Keyboard.TypeAsync(text);15 }16 public static async Task OvertypeInputAsync(this Page page, string selector, string text)17 {18 await page.WaitForSelectorAsync(selector);19 await page.FocusAsync(selector);20 await page.Keyboard.DownAsync("Control");21 await page.Keyboard.PressAsync("A");22 await page.Keyboard.UpAsync("Control");23 await page.Keyboard.PressAsync("Backspace");24 await page.Keyboard.TypeAsync(text);25 }26 public static async Task ClickOn(this Page page, string selector)27 {28 await page.WaitForSelectorAsync(selector);29 await page.ClickAsync(selector);30 }31 }32}...
FocusAsync
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 {11 var page = await browser.NewPageAsync();12 await page.FocusAsync("input[name='q']");13 }14 }15 }16}
FocusAsync
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static async Task Main(string[] args)7 {8 var browser = await Puppeteer.LaunchAsync(new LaunchOptions9 {10 });11 var page = await browser.NewPageAsync();12 await page.FocusAsync("input[name=q]");13 await page.TypeAsync("input[name=q]", "PuppeteerSharp");14 await page.Keyboard.PressAsync("Enter");15 await page.ScreenshotAsync("screenshot.png");16 await browser.CloseAsync();17 }18 }19}
FocusAsync
Using AI Code Generation
1var page = await browser.NewPageAsync();2await page.FocusAsync("input[type='text']");3var frame = page.MainFrame;4await frame.FocusAsync("input[type='text']");5var elementHandle = await page.QuerySelectorAsync("input[type='text']");6await elementHandle.FocusAsync();
FocusAsync
Using AI Code Generation
1public async Task FocusAsyncTests()2{3 {4 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"5 };6 var browser = await Puppeteer.LaunchAsync(options);7 var page = await browser.NewPageAsync();8 await page.FocusAsync("input[title='Search']");9 await page.Keyboard.TypeAsync("Hello World");10}11public async Task FocusAsyncTests()12{13 {14 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"15 };16 var browser = await Puppeteer.LaunchAsync(options);17 var page = await browser.NewPageAsync();18 await page.MainFrame.FocusAsync("input[title='Search']");19 await page.Keyboard.TypeAsync("Hello World");20}21public async Task FocusAsyncTests()22{23 {24 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"25 };26 var browser = await Puppeteer.LaunchAsync(options);27 var page = await browser.NewPageAsync();28 var elementHandle = await page.QuerySelectorAsync("input[title='Search']");29 await elementHandle.FocusAsync();30 await page.Keyboard.TypeAsync("Hello World");31}32public async Task FocusAsyncTests()33{34 {35 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"36 };37 var browser = await Puppeteer.LaunchAsync(options);38 var page = await browser.NewPageAsync();39 var jSHandle = await page.EvaluateExpressionHandleAsync("document.querySelector('input
FocusAsync
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 await page.FocusAsync("input[name='q']");14 await page.ScreenshotAsync("google.png");15 await browser.CloseAsync();16 }17 }18}
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!!