Best Puppeteer-sharp code snippet using PuppeteerSharp.Page.ClickAsync
WebScraper.cs
Source:WebScraper.cs
...171 /// </summary>172 /// <param name="button">Mouse button to simulate.</param>173 public void MouseClick(MouseButton button)174 {175 MouseClickAsync(button).Wait();176 }177 private async Task MouseClickAsync(MouseButton button)178 {179 await m_page.Mouse.ClickAsync(m_MouseX, m_MouseY, new ClickOptions{ Button = button == MouseButton.Left ? PuppeteerSharp.Input.MouseButton.Left : PuppeteerSharp.Input.MouseButton.Right });180 }181 /// <summary>182 /// Simulates a mouse up event on page.183 /// </summary>184 /// <param name="button">Mouse button to simulate.</param>185 public void MouseUp(MouseButton button)186 {187 MouseUpAsync(button).Wait();188 189 }190 private async Task MouseUpAsync(MouseButton button)191 {192 await m_page.Mouse.UpAsync(new ClickOptions { Button = button == MouseButton.Left ? PuppeteerSharp.Input.MouseButton.Left : PuppeteerSharp.Input.MouseButton.Right });193 }194 /// <summary>195 /// Simulates a mouse down event on page.196 /// </summary>197 /// <param name="button">Mouse button to simulate.</param>198 public void MouseDown(MouseButton button)199 {200 MouseDownAsync(button).Wait();201 }202 private async Task MouseDownAsync(MouseButton button)203 {204 await m_page.Mouse.DownAsync(new ClickOptions { Button = button == MouseButton.Left ? PuppeteerSharp.Input.MouseButton.Left : PuppeteerSharp.Input.MouseButton.Right });205 }206 /// <summary>207 /// Simulates a touch tap on a page.208 /// </summary>209 /// <param name="target">Javascript selector for element to tap on.</param>210 public void TapScreen(string target)211 {212 TapScreenAsync(target).Wait();213 }214 private async Task TapScreenAsync(string target)215 {216 await m_page.TapAsync(target);217 }218 /// <summary>219 /// Generates a pdf of the page.220 /// </summary>221 /// <returns>Stream containing the pdf data.</returns>222 public Stream CreatePdf()223 {224 var data = CreatePdfAsync();225 data.Wait();226 return data.Result;227 }228 private async Task<Stream> CreatePdfAsync()229 {230 return await m_page.PdfStreamAsync();231 }232 /// <summary>233 /// Waits for expression to be to be true.234 /// </summary>235 /// <param name="expression">Expression to wait on.</param>236 public void WaitOnScript(string expression)237 {238 WaitOnScriptAsync(expression).Wait();239 }240 private async Task WaitOnScriptAsync(string expression)241 {242 await m_page.WaitForExpressionAsync(expression);243 }244 /// <summary>245 /// Selects element on page to have focus.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>269 /// Html content of page. Useful for scraping the html directly.270 /// </summary>271 public string Content272 {273 get274 {275 var data = m_page.GetContentAsync();276 data.Wait();277 return data.Result;278 }279 set280 {...
Program.cs
Source:Program.cs
...44 await SetDropdownValue(page, "state", "VA");45 var zipSelector = "#zip";46 await TypeFieldValue(page, zipSelector, "22015", delay);47 /// Same as Billing checkbox48 await page.ClickAsync("#same-address");49 await page.Keyboard.PressAsync("Tab");50 /// Save Information checkbox51 await page.ClickAsync("#save-info");52 await page.Keyboard.PressAsync("Tab");53 /// PayPal radio button54 await page.ClickAsync("#paypal");55 await page.Keyboard.PressAsync("Tab");56 await ClickHyperlinkWithText(page, "Matlus");57 await MatlusWebsiteOperations(page);58 await page.ScreenshotAsync("Screenshot.jpg", new ScreenshotOptions { FullPage = true, Quality = 100 });59 await browser.CloseAsync();60 }61 private static async void Page_Response(object sender, ResponseCreatedEventArgs e)62 {63 Console.WriteLine(e.Response.Status);64 }65 private static void Page_Request(object sender, RequestEventArgs e)66 {67 Console.WriteLine(e.Request.ResourceType.ToString());68 Console.WriteLine(e.Request.Url);69 }70 private static async Task MatlusWebsiteOperations(Page page)71 {72 await ClickElementWithXPathAndWaitForXPath(page, "//a[text()='2']", "//a[text()='1']");73 ////await ClickLinkWithSelectorAndWaitForSelector(page, "a[data-pageno=\"2\"]", "a[data-pageno=\"1\"]");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 else110 {111 throw new Exception($"A hyperlink with the text: {hyperlinkText} was not found");112 } 113 }114 private static async Task ClickLinkWithSelectorAndWaitForSelector(Page page, string linkSelector, string waitForSelector)115 {116 await page.ClickAsync(linkSelector);117 await page.WaitForSelectorAsync($"{ waitForSelector}");118 }119 private static async Task ClickElementWithXPathAndWaitForXPath(Page page, string clickOnXpathExpression, string waitForXpathExpression)120 {121 var aElementsWithRestful = await page.XPathAsync(clickOnXpathExpression);122 if (aElementsWithRestful.Length == 1)123 {124 var navigationTask = page.WaitForXPathAsync(waitForXpathExpression);125 var clickTask = aElementsWithRestful[0].ClickAsync();126 await Task.WhenAll(navigationTask, clickTask);127 }128 else129 {130 throw new Exception($"A hyperlink with expression: {clickOnXpathExpression} was not found");131 }132 }133 }134}...
AccountsControllerIntegrationTests.cs
Source:AccountsControllerIntegrationTests.cs
...59 {60 // 3. Navigate to the test client page61 await page.GoToAsync($"http://{_webHostFixture.Host}/test-client/index.html");62 var navigationTask = page.WaitForNavigationAsync();63 await Task.WhenAll(navigationTask, page.ClickAsync("button"));64 // 4. Fill out the login form65 await page.TypeAsync("#Username", _signupRequests[1].Email);66 await page.TypeAsync("#Password", _signupRequests[1].Password);67 // 5. Hit the login button and wait for redirect navigation...68 navigationTask = page.WaitForNavigationAsync(new NavigationOptions { WaitUntil = new[] { WaitUntilNavigation.Networkidle0 } });69 await Task.WhenAll(navigationTask, page.ClickAsync(".btn-primary"));70 var content = await page.GetContentAsync();71 await page.CloseAsync();72 // 6. Assert we have a logged-in state in the test client73 Assert.Contains("User logged in", content);74 Assert.Contains("Prescott Terrell", content);75 Assert.Contains("pterrell@mailinator.com", content);76 Assert.Contains("employer", content);77 }78 }79 }80 }81}...
TimeTrackingController.cs
Source:TimeTrackingController.cs
...33 34 await page.GoToAsync(@"https://timetracker.bairesdev.com/");35 await page.TypeAsync("#ctl00_ContentPlaceHolder_UserNameTextBox", tracking.User);36 await page.TypeAsync("#ctl00_ContentPlaceHolder_PasswordTextBox", tracking.Password);37 await page.ClickAsync("#ctl00_ContentPlaceHolder_LoginButton");38 await page.GoToAsync(@"https://timetracker.bairesdev.com/CargaTimeTracker.aspx");39 40 await page.EvaluateExpressionAsync($@"document.querySelector('#ctl00_ContentPlaceHolder_txtFrom').value = null");41 await page.TypeAsync("#ctl00_ContentPlaceHolder_txtFrom", tracking.Date, new TypeOptions{ Delay = 30 });42 var dropProject = await page.QuerySelectorAsync("#ctl00_ContentPlaceHolder_idProyectoDropDownList");43 await dropProject.ClickAsync();44 45 var children = await dropProject.QuerySelectorAllAsync("option");46 await children[2].ClickAsync();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 ...
SpotifyClient.cs
Source:SpotifyClient.cs
...45 }46 public async Task SubmitLogin()47 {48 await Task.WhenAll(49 _view.ClickAsync("#login-button"),50 _view.WaitForNavigationAsync()51 );52 }53 public async Task GoToTokenView()54 {55 await _view.GoToAsync("https://developer.spotify.com/console/post-playlist-tracks/");56 }57 public async Task ShowPrivilegeDialog()58 {59 var btnRequestToken = await _view.XPathAsync("//*[@id='console-form']/div[4]/div/span/button");60 await btnRequestToken[0].ClickAsync();61 }62 public async Task FillPrivilegeForm()63 {64 await _view.ClickAsync("#scope-playlist-modify-public");65 await _view.ClickAsync("#scope-playlist-modify-private");66 }67 public async Task AgreePolicy()68 {69 var btnAgree = await _view.XPathAsync("//div[@id='onetrust-close-btn-container']/button");70 await btnAgree[0].ClickAsync();71 }72 public async Task<bool> IsPolicyPresent()73 {74 var btnAgree = await _view.QuerySelectorAsync("#onetrust-close-btn-container");75 return btnAgree != null;76 }77 public async Task SubmitPrivilegeForm()78 {79 await _view.ClickAsync("#oauthRequestToken");80 }81 public async Task Sleep(int timeout)82 {83 await _view.WaitForTimeoutAsync(timeout);84 }85 public async Task<string> GetOAuthToken()86 {87 return await _view.EvaluateExpressionAsync<string>("document.getElementById('oauth-input').value");88 }89 }90}...
Clean163Email.cs
Source:Clean163Email.cs
...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);58 await confirm2Btn.ClickAsync();59 }60 catch (Exception e)61 {62 Console.WriteLine(e);63 }64 }65 }66 }67 }68}...
MakeTweet.cs
Source:MakeTweet.cs
...40 public static async Task makeTweetAsync(String str)41 {42 await page.SetCacheEnabledAsync(true);43 await page.SetJavaScriptEnabledAsync(true);44 await page.ClickAsync("a[data-testid='SideNav_NewTweet_Button']");45 await page.ClickAsync("div[data-testid='tweetTextarea_0']");46 TypeOptions op = new TypeOptions();47 op.Delay = 10;48 await page.TypeAsync("div[data-testid='tweetTextarea_0']", str,op);49 await page.ClickAsync("div[data-testid='tweetButton']");50 await page.WaitForNavigationAsync();51 //await browser.CloseAsync();52 }53 }54}...
LogoutAwaiter.cs
Source:LogoutAwaiter.cs
...18 {19 var menuElement = await page.QuerySelectorAsync(MENU_IMAGE);20 if(!(menuElement is null))21 {22 await menuElement.ClickAsync();23 var logoutElement = await page.QuerySelectorAsync(LOGOUT_IMAGE);24 if (!(logoutElement is null))25 {26 await logoutElement.ClickAsync();27 break;28 }29 }30 }31 while (DateTime.Now.Subtract(startDate) < timeout);32 Thread.Sleep(1000);33 }34 }35}...
ClickAsync
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 await page.ClickAsync("input[name='q']");12 await page.Keyboard.TypeAsync("Puppeteer Sharp");13 await page.ClickAsync("input[name='btnK']");14 await page.WaitForSelectorAsync("h3");15 Console.WriteLine(await page.GetContentAsyn
ClickAsync
Using AI Code Generation
1await page.ClickAsync("button");2await frame.ClickAsync("button");3await page.ClickAsync("button");4await frame.ClickAsync("button");5await page.ClickAsync("button");6await frame.ClickAsync("button");
ClickAsync
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4using System.Diagnostics;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.ClickAsync("input[name='q']", new ClickOptions { Delay = 5000 });14 await page.TypeAsync("input[name='q']", "PuppeteerSharp");15 await page.Keyboard.PressAsync("Enter");16 await page.ScreenshotAsync("screenshot.png");17 await browser.CloseAsync();18 }19}
ClickAsync
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.ClickAsync("input[name=q]");14 await page.Keyboard.TypeAsync("PuppeteerSharp");15 await page.Keyboard.PressAsync("Enter");16 await page.ScreenshotAsync("screenshot.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 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);29 var browser = await Puppeteer.LaunchAsync(new LaunchOptions30 {31 });32 var page = await browser.NewPageAsync();33 var elementHandle = await page.QuerySelectorAsync("input[name=q]");34 await elementHandle.ClickAsync();35 await page.Keyboard.TypeAsync("PuppeteerSharp");36 await page.Keyboard.PressAsync("Enter");37 await page.ScreenshotAsync("screenshot.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 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);50 var browser = await Puppeteer.LaunchAsync(new LaunchOptions51 {52 });53 var page = await browser.NewPageAsync();
ClickAsync
Using AI Code Generation
1using System.Threading.Tasks;2using PuppeteerSharp;3{4 {5 static async Task Main(string[] args)6 {7 var options = new LaunchOptions { Headless = false };8 using (var browser = await Puppeteer.LaunchAsync(options))9 {10 using (var page = await browser.NewPageAsync())11 {12 await page.ClickAsync("input[name='q']");13 await page.Keyboard.TypeAsync("PuppeteerSharp");14 await page.Keyboard.PressAsync("Enter");15 await page.ScreenshotAsync("google.png");16 }17 }18 }19 }20}21using System.Threading.Tasks;22using PuppeteerSharp;23{24 {25 static async Task Main(string[] args)26 {27 var options = new LaunchOptions { Headless = false };28 using (var browser = await Puppeteer.LaunchAsync(options))29 {30 using (var page = await browser.NewPageAsync())31 {32 await page.TypeAsync("input[name='q']", "PuppeteerSharp");33 await page.Keyboard.PressAsync("Enter");34 await page.ScreenshotAsync("google.png");35 }36 }37 }38 }39}40using System.Threading.Tasks;41using PuppeteerSharp;42{43 {44 static async Task Main(string[] args)45 {46 var options = new LaunchOptions { Headless = false };47 using (var browser = await Puppeteer.LaunchAsync(options))48 {49 using (var page = await browser.NewPageAsync())50 {51 await page.TypeAsync("input[name='q']", "PuppeteerSharp");52 await page.PressAsync("input[name='q']", "Enter");53 await page.ScreenshotAsync("google
ClickAsync
Using AI Code Generation
1await page.ClickAsync("button");2await page.ClickAsync("a");3await page.ClickAsync("img");4await page.ClickAsync("div");5await page.ClickAsync("span");6await page.ClickAsync("td");7await page.ClickAsync("tr");8await page.ClickAsync("th");9await page.ClickAsync("li");10await page.ClickAsync("ul");11await page.ClickAsync("ol");12await page.ClickAsync("h1");13await page.ClickAsync("h2");14await page.ClickAsync("h3");15await page.ClickAsync("h4");16await page.ClickAsync("h5");17await page.ClickAsync("h6");18await page.ClickAsync("p");19await page.ClickAsync("input");20await page.ClickAsync("select");21await page.ClickAsync("option");22await page.ClickAsync("textarea");23await page.ClickAsync("form");24await page.ClickAsync("table");
ClickAsync
Using AI Code Generation
1await page.ClickAsync("text=Click me");2await page.ClickAsync("text=Click me", new ClickOptions { Button = MouseButton.Middle });3await page.ClickAsync("text=Click me", new ClickOptions { ClickCount = 2 });4await page.ClickAsync("text=Click me", new ClickOptions { Delay = 1000 });5await page.ClickAsync("text=Click me", new ClickOptions { Position = new Point(1, 1) });6await page.ClickAsync("text=Click me", new ClickOptions { Button = MouseButton.Middle, ClickCount = 2, Delay = 1000, Position = new Point(1, 1) });7await page.ClickAsync("text=Click me", new ClickOptions { Button = MouseButton.Middle, ClickCount = 2, Delay = 1000, Position = new Point(1, 1) });8await page.ClickAsync("text=Click me", new ClickOptions { Button = MouseButton.Middle, ClickCount = 2, Delay = 1000, Position = new Point(1, 1) });9await page.ClickAsync("text=Click me", new ClickOptions { Button = MouseButton.Middle, ClickCount = 2, Delay = 1000, Position = new Point(1, 1) });
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!!