Best Puppeteer-sharp code snippet using PuppeteerSharp.Frame.GoToAsync
PuppeteerMethods.cs
Source:PuppeteerMethods.cs
...37 {38 try39 {40 WaitUntilNavigation[] waitUntil = new[] { WaitUntilNavigation.Networkidle0, WaitUntilNavigation.Networkidle2, WaitUntilNavigation.DOMContentLoaded, WaitUntilNavigation.Load };41 await page.GoToAsync("http://www.google.com", new NavigationOptions { WaitUntil = waitUntil });42 var filePath = "D:\\PdfFiles";43 var fileName = Guid.NewGuid() + ".pdf";44 if (!Directory.Exists(filePath))45 Directory.CreateDirectory(filePath);46 await page.PdfAsync(Path.Combine(filePath, fileName));47 return new SuccessPuppeteerResult("Pdf Created Succesfully");48 }49 catch (Exception ex)50 {51 return new ErrorPuppeteerResult("Error Occured! Detail: " + ex.Message);52 }53 finally54 {55 CloseChromium(page);56 }57 }58 }59 public static async Task<PuppeteerResult> TakeScreenShot(string url)60 {61 using (var page = await OpenChromiumPage())62 {63 try64 {65 WaitUntilNavigation[] waitUntil = new[] { WaitUntilNavigation.Networkidle0, WaitUntilNavigation.Networkidle2, WaitUntilNavigation.DOMContentLoaded, WaitUntilNavigation.Load };66 await page.GoToAsync(url, new NavigationOptions { WaitUntil = waitUntil });67 var filePath = "D:\\Screenshots";68 var fileName = Guid.NewGuid() + ".png";69 if (!Directory.Exists(filePath))70 Directory.CreateDirectory(filePath);71 await page.SetViewportAsync(new ViewPortOptions72 {73 Width = 1280,74 Height = 72075 });76 await page.ScreenshotAsync(Path.Combine(filePath, fileName));77 return new SuccessPuppeteerResult("Screenshot has taken succesfully");78 }79 catch (Exception ex)80 {81 return new ErrorPuppeteerResult("Error Occured! Detail: " + ex.Message);82 }83 finally84 {85 CloseChromium(page);86 }87 }88 }89 public static async Task<string> TakeHtmlContent()90 {91 using (var page = await OpenChromiumPage())92 {93 WaitUntilNavigation[] waitUntil = new[] { WaitUntilNavigation.Networkidle0, WaitUntilNavigation.Networkidle2, WaitUntilNavigation.DOMContentLoaded, WaitUntilNavigation.Load };94 await page.GoToAsync("http://www.google.com", new NavigationOptions { WaitUntil = waitUntil });95 return await page.GetContentAsync();96 }97 }98 public static async Task<string> SetHtmlToPage()99 {100 using (var page = await OpenChromiumPage())101 {102 WaitUntilNavigation[] waitUntil = new[] { WaitUntilNavigation.Networkidle0, WaitUntilNavigation.Networkidle2, WaitUntilNavigation.DOMContentLoaded, WaitUntilNavigation.Load };103 await page.SetContentAsync("<div><h1>Hello World!</h1></div>");104 return await page.GetContentAsync();105 }106 }107 public static async Task<PuppeteerDataResult<string>> GetTitleOfPage(string url)108 {109 using (var page = await OpenChromiumPage())110 {111 try112 {113 WaitUntilNavigation[] waitUntil = new[] { WaitUntilNavigation.Networkidle0, WaitUntilNavigation.Networkidle2, WaitUntilNavigation.DOMContentLoaded, WaitUntilNavigation.Load };114 await page.GoToAsync(url, new NavigationOptions { WaitUntil = waitUntil });115 var title = await page.GetTitleAsync();116 return new SuccessPuppeteerDataResult<string>(title, "Get Title Successfully");117 }118 catch (Exception ex)119 {120 return new ErrorPuppeteerDataResult<string>("Error Occured! Detail: " + ex.Message);121 }122 finally123 {124 CloseChromium(page);125 }126 }127 }128 public static async Task<Frame[]> GetAllFrames()129 {130 using (var page = await OpenChromiumPage())131 {132 WaitUntilNavigation[] waitUntil = new[] { WaitUntilNavigation.Networkidle0, WaitUntilNavigation.Networkidle2, WaitUntilNavigation.DOMContentLoaded, WaitUntilNavigation.Load };133 await page.GoToAsync("https://www.google.com", new NavigationOptions { WaitUntil = waitUntil });134 return page.Frames;135 }136 }137 public static async Task<PuppeteerResult> LoginFacebook(string username, string password)138 {139 using (var page = await OpenChromiumPage())140 {141 try142 {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']");...
WaitForNavigationTests.cs
Source:WaitForNavigationTests.cs
...13 }14 [Fact]15 public async Task ShouldWork()16 {17 await Page.GoToAsync(TestConstants.EmptyPage);18 var waitForNavigationResult = Page.WaitForNavigationAsync();19 await Task.WhenAll(20 waitForNavigationResult,21 Page.EvaluateFunctionAsync("url => window.location.href = url", TestConstants.ServerUrl + "/grid.html")22 );23 var response = await waitForNavigationResult;24 Assert.Equal(HttpStatusCode.OK, response.Status);25 Assert.Contains("grid.html", response.Url);26 }27 [Fact]28 public async Task ShouldWorkWithBothDomcontentloadedAndLoad()29 {30 var responseCompleted = new TaskCompletionSource<bool>();31 Server.SetRoute("/one-style.css", context =>32 {33 return responseCompleted.Task;34 });35 var waitForRequestTask = Server.WaitForRequest("/one-style.css");36 var navigationTask = Page.GoToAsync(TestConstants.ServerUrl + "/one-style.html");37 var domContentLoadedTask = Page.WaitForNavigationAsync(new NavigationOptions38 {39 WaitUntil = new[] { WaitUntilNavigation.DOMContentLoaded }40 });41 var bothFired = false;42 var bothFiredTask = Page.WaitForNavigationAsync(new NavigationOptions43 {44 WaitUntil = new[]45 {46 WaitUntilNavigation.Load,47 WaitUntilNavigation.DOMContentLoaded48 }49 }).ContinueWith(_ => bothFired = true);50 await waitForRequestTask.WithTimeout();51 await domContentLoadedTask.WithTimeout();52 Assert.False(bothFired);53 responseCompleted.SetResult(true);54 await bothFiredTask.WithTimeout();55 await navigationTask.WithTimeout();56 }57 [Fact]58 public async Task ShouldWorkWithClickingOnAnchorLinks()59 {60 await Page.GoToAsync(TestConstants.EmptyPage);61 await Page.SetContentAsync("<a href='#foobar'>foobar</a>");62 var navigationTask = Page.WaitForNavigationAsync();63 await Task.WhenAll(64 navigationTask,65 Page.ClickAsync("a")66 );67 Assert.Null(await navigationTask);68 Assert.Equal(TestConstants.EmptyPage + "#foobar", Page.Url);69 }70 [Fact]71 public async Task ShouldWorkWithHistoryPushState()72 {73 await Page.GoToAsync(TestConstants.EmptyPage);74 await Page.SetContentAsync(@"75 <a onclick='javascript:pushState()'>SPA</a>76 <script>77 function pushState() { history.pushState({}, '', 'wow.html') }78 </script>79 ");80 var navigationTask = Page.WaitForNavigationAsync();81 await Task.WhenAll(82 navigationTask,83 Page.ClickAsync("a")84 );85 Assert.Null(await navigationTask);86 Assert.Equal(TestConstants.ServerUrl + "/wow.html", Page.Url);87 }88 [Fact]89 public async Task ShouldWorkWithHistoryReplaceState()90 {91 await Page.GoToAsync(TestConstants.EmptyPage);92 await Page.SetContentAsync(@"93 <a onclick='javascript:pushState()'>SPA</a>94 <script>95 function pushState() { history.pushState({}, '', 'replaced.html') }96 </script>97 ");98 var navigationTask = Page.WaitForNavigationAsync();99 await Task.WhenAll(100 navigationTask,101 Page.ClickAsync("a")102 );103 Assert.Null(await navigationTask);104 Assert.Equal(TestConstants.ServerUrl + "/replaced.html", Page.Url);105 }106 [Fact]107 public async Task ShouldWorkWithDOMHistoryBackAndHistoryForward()108 {109 await Page.GoToAsync(TestConstants.EmptyPage);110 await Page.SetContentAsync(@"111 <a id=back onclick='javascript:goBack()'>back</a>112 <a id=forward onclick='javascript:goForward()'>forward</a>113 <script>114 function goBack() { history.back(); }115 function goForward() { history.forward(); }116 history.pushState({}, '', '/first.html');117 history.pushState({}, '', '/second.html');118 </script>119 ");120 Assert.Equal(TestConstants.ServerUrl + "/second.html", Page.Url);121 var navigationTask = Page.WaitForNavigationAsync();122 await Task.WhenAll(123 navigationTask,124 Page.ClickAsync("a#back")125 );126 Assert.Null(await navigationTask);127 Assert.Equal(TestConstants.ServerUrl + "/first.html", Page.Url);128 navigationTask = Page.WaitForNavigationAsync();129 await Task.WhenAll(130 navigationTask,131 Page.ClickAsync("a#forward")132 );133 Assert.Null(await navigationTask);134 Assert.Equal(TestConstants.ServerUrl + "/second.html", Page.Url);135 }136 [Fact]137 public async Task ShouldWorkWhenSubframeIssuesWindowStop()138 {139 Server.SetRoute("/frames/style.css", (context) => Task.CompletedTask);140 var navigationTask = Page.GoToAsync(TestConstants.ServerUrl + "/frames/one-frame.html");141 var frameAttachedTaskSource = new TaskCompletionSource<Frame>();142 Page.FrameAttached += (sender, e) =>143 {144 frameAttachedTaskSource.SetResult(e.Frame);145 };146 var frame = await frameAttachedTaskSource.Task;147 var frameNavigatedTaskSource = new TaskCompletionSource<bool>();148 Page.FrameNavigated += (sender, e) =>149 {150 if (e.Frame == frame)151 {152 frameNavigatedTaskSource.TrySetResult(true);153 }154 };...
FrameManagementTests.cs
Source:FrameManagementTests.cs
...13 }14 [Fact]15 public async Task ShouldHandleNestedFrames()16 {17 await Page.GoToAsync(TestConstants.ServerUrl + "/frames/nested-frames.html");18 Assert.Equal(TestConstants.NestedFramesDumpResult, FrameUtils.DumpFrames(Page.MainFrame));19 }20 [Fact]21 public async Task ShouldSendEventsWhenFramesAreManipulatedDynamically()22 {23 await Page.GoToAsync(TestConstants.EmptyPage);24 // validate frameattached events25 var attachedFrames = new List<Frame>();26 Page.FrameAttached += (sender, e) => attachedFrames.Add(e.Frame);27 await FrameUtils.AttachFrameAsync(Page, "frame1", "./assets/frame.html");28 Assert.Single(attachedFrames);29 Assert.Contains("/assets/frame.html", attachedFrames[0].Url);30 // validate framenavigated events31 var navigatedFrames = new List<Frame>();32 Page.FrameNavigated += (sender, e) => navigatedFrames.Add(e.Frame);33 await FrameUtils.NavigateFrameAsync(Page, "frame1", "./empty.html");34 Assert.Single(navigatedFrames);35 Assert.Equal(TestConstants.EmptyPage, navigatedFrames[0].Url);36 // validate framedetached events37 var detachedFrames = new List<Frame>();38 Page.FrameDetached += (sender, e) => detachedFrames.Add(e.Frame);39 await FrameUtils.DetachFrameAsync(Page, "frame1");40 Assert.Single(navigatedFrames);41 Assert.True(navigatedFrames[0].Detached);42 }43 [Fact]44 public async Task ShouldPersistMainFrameOnCrossProcessNavigation()45 {46 await Page.GoToAsync(TestConstants.EmptyPage);47 var mainFrame = Page.MainFrame;48 await Page.GoToAsync(TestConstants.CrossProcessUrl + "/empty.html");49 Assert.Equal(mainFrame, Page.MainFrame);50 }51 [Fact]52 public async Task ShouldNotSendAttachDetachEventsForMainFrame()53 {54 var hasEvents = false;55 Page.FrameAttached += (sender, e) => hasEvents = true;56 Page.FrameDetached += (sender, e) => hasEvents = true;57 await Page.GoToAsync(TestConstants.EmptyPage);58 Assert.False(hasEvents);59 }60 [Fact]61 public async Task ShouldDetachChildFramesOnNavigation()62 {63 var attachedFrames = new List<Frame>();64 var detachedFrames = new List<Frame>();65 var navigatedFrames = new List<Frame>();66 Page.FrameAttached += (sender, e) => attachedFrames.Add(e.Frame);67 Page.FrameDetached += (sender, e) => detachedFrames.Add(e.Frame);68 Page.FrameNavigated += (sender, e) => navigatedFrames.Add(e.Frame);69 await Page.GoToAsync(TestConstants.ServerUrl + "/frames/nested-frames.html");70 Assert.Equal(4, attachedFrames.Count);71 Assert.Empty(detachedFrames);72 Assert.Equal(5, navigatedFrames.Count);73 attachedFrames.Clear();74 detachedFrames.Clear();75 navigatedFrames.Clear();76 await Page.GoToAsync(TestConstants.EmptyPage);77 Assert.Empty(attachedFrames);78 Assert.Equal(4, detachedFrames.Count);79 Assert.Single(navigatedFrames);80 }81 [Fact]82 public async Task ShouldReportFrameName()83 {84 await FrameUtils.AttachFrameAsync(Page, "theFrameId", TestConstants.EmptyPage);85 await Page.EvaluateFunctionAsync(@"url => {86 const frame = document.createElement('iframe');87 frame.name = 'theFrameName';88 frame.src = url;89 document.body.appendChild(frame);90 return new Promise(x => frame.onload = x);...
AuthIntegrationTests.cs
Source:AuthIntegrationTests.cs
...21 Browser browser22 )23 {24 var page = await browser.NewPageAsync();25 await page.GoToAsync(app.RootUri.ToString());26 // We should be redirected to login27 new Uri(page.Url).AbsolutePath.Should().Be("/login");28 }29 [Test]30 [Auto]31 public async Task SignupThenLogin(32 AppFactory app,33 Browser browser34 )35 {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 }...
RequestFrameTests.cs
Source:RequestFrameTests.cs
...25 {26 requests.Add(e.Request);27 }28 };29 await Page.GoToAsync(TestConstants.EmptyPage);30 Assert.Single(requests);31 Assert.Equal(Page.MainFrame, requests[0].Frame);32 }33 [PuppeteerTest("network.spec.ts", "Request.Frame", "should work for subframe navigation request")]34 [PuppeteerFact]35 public async Task ShouldWorkForSubframeNavigationRequest()36 {37 var requests = new List<Request>();38 Page.Request += (_, e) =>39 {40 if (!TestUtils.IsFavicon(e.Request))41 {42 requests.Add(e.Request);43 }44 };45 await Page.GoToAsync(TestConstants.EmptyPage);46 await FrameUtils.AttachFrameAsync(Page, "frame1", TestConstants.EmptyPage);47 Assert.Equal(2, requests.Count);48 Assert.Equal(Page.FirstChildFrame(), requests[1].Frame);49 }50 [PuppeteerTest("network.spec.ts", "Request.Frame", "should work for fetch requests")]51 [PuppeteerFact]52 public async Task ShouldWorkForFetchRequests()53 {54 var requests = new List<Request>();55 Page.Request += (_, e) =>56 {57 if (!TestUtils.IsFavicon(e.Request))58 {59 requests.Add(e.Request);60 }61 };62 await Page.GoToAsync(TestConstants.EmptyPage);63 await Page.EvaluateExpressionAsync("fetch('/empty.html')");64 Assert.Equal(2, requests.Count);65 Assert.Equal(Page.MainFrame, requests[0].Frame);66 }67 }68}...
FrameEvaluateTests.cs
Source:FrameEvaluateTests.cs
...15 [PuppeteerTest("evaluation.spec.ts", "Frame.evaluate", "should have different execution contexts")]16 [PuppeteerFact]17 public async Task ShouldHaveDifferentExecutionContexts()18 {19 await Page.GoToAsync(TestConstants.EmptyPage);20 await FrameUtils.AttachFrameAsync(Page, "frame1", TestConstants.EmptyPage);21 Assert.Equal(2, Page.Frames.Count());22 var frame1 = Page.MainFrame;23 var frame2 = Page.FirstChildFrame();24 await frame1.EvaluateExpressionAsync("window.FOO = 'foo'");25 await frame2.EvaluateExpressionAsync("window.FOO = 'bar'");26 Assert.Equal("foo", await frame1.EvaluateExpressionAsync<string>("window.FOO"));27 Assert.Equal("bar", await frame2.EvaluateExpressionAsync<string>("window.FOO"));28 }29 [PuppeteerTest("evaluation.spec.ts", "Frame.evaluate", "should execute after cross-site navigation")]30 [PuppeteerFact]31 public async Task ShouldExecuteAfterCrossSiteNavigation()32 {33 await Page.GoToAsync(TestConstants.EmptyPage);34 var mainFrame = Page.MainFrame;35 Assert.Contains("localhost", await mainFrame.EvaluateExpressionAsync<string>("window.location.href"));36 await Page.GoToAsync(TestConstants.CrossProcessHttpPrefix + "/empty.html");37 Assert.Contains("127", await mainFrame.EvaluateExpressionAsync<string>("window.location.href"));38 }39 }40}...
EvaluateTests.cs
Source:EvaluateTests.cs
...12 }13 [Fact]14 public async Task ShouldHaveDifferentExecutionContexts()15 {16 await Page.GoToAsync(TestConstants.EmptyPage);17 await FrameUtils.AttachFrameAsync(Page, "frame1", TestConstants.EmptyPage);18 Assert.Equal(2, Page.Frames.Count());19 var frame1 = Page.Frames.ElementAt(0);20 var frame2 = Page.Frames.ElementAt(1);21 await frame1.EvaluateExpressionAsync("window.FOO = 'foo'");22 await frame2.EvaluateExpressionAsync("window.FOO = 'bar'");23 Assert.Equal("foo", await frame1.EvaluateExpressionAsync<string>("window.FOO"));24 Assert.Equal("bar", await frame2.EvaluateExpressionAsync<string>("window.FOO"));25 }26 [Fact]27 public async Task ShouldExecuteAfterCrossSiteNavigation()28 {29 await Page.GoToAsync(TestConstants.EmptyPage);30 var mainFrame = Page.MainFrame;31 Assert.Contains("localhost", await mainFrame.EvaluateExpressionAsync<string>("window.location.href"));32 await Page.GoToAsync(TestConstants.CrossProcessHttpPrefix + "/empty.html");33 Assert.Contains("127", await mainFrame.EvaluateExpressionAsync<string>("window.location.href"));34 }35 }36}...
PuppeteerExtensions.cs
Source:PuppeteerExtensions.cs
...27 public static async Task<bool> NavigateAndWait(this Page page, string url)28 {29 try30 {31 return (await page.GoToAsync(url, 15000, new[] { WaitUntilNavigation.Networkidle2 })).Ok;32 }33 catch (System.Exception)34 {35 return false;36 }37 }38 }39}...
GoToAsync
Using AI Code Generation
1var page = await browser.NewPageAsync();2await page.ScreenshotAsync("1.png");3var page = await browser.NewPageAsync();4await page.ScreenshotAsync("2.png");5var page = await browser.NewPageAsync();6await page.ScreenshotAsync("3.png");7var page = await browser.NewPageAsync();8await page.ScreenshotAsync("4.png");9var page = await browser.NewPageAsync();10await page.ScreenshotAsync("5.png");11var page = await browser.NewPageAsync();12await page.ScreenshotAsync("6.png");13var page = await browser.NewPageAsync();14await page.ScreenshotAsync("7.png");15var page = await browser.NewPageAsync();16await page.ScreenshotAsync("8.png");17var page = await browser.NewPageAsync();18await page.ScreenshotAsync("9.png");19var page = await browser.NewPageAsync();20await page.ScreenshotAsync("10.png");
GoToAsync
Using AI Code Generation
1var page = await browser.NewPageAsync();2var page = await browser.NewPageAsync();3var page = await browser.NewPageAsync();4var page = await browser.NewPageAsync();5var page = await browser.NewPageAsync();6var page = await browser.NewPageAsync();7var page = await browser.NewPageAsync();8var page = await browser.NewPageAsync();9var page = await browser.NewPageAsync();
GoToAsync
Using AI Code Generation
1var page = await browser.NewPageAsync();2await page.WaitForSelectorAsync("input[name='q']");3await page.ClickAsync("input[name='q']");4await page.TypeAsync("PuppeteerSharp");5await page.Keyboard.PressAsync("Enter");6await page.WaitForNavigationAsync();7await page.ScreenshotAsync("google.png");8var page = await browser.NewPageAsync();9await page.WaitForSelectorAsync("input[name='q']");10await page.ClickAsync("input[name='q']");11await page.TypeAsync("PuppeteerSharp");12await page.Keyboard.PressAsync("Enter");13await page.WaitUntilNavigationAsync();14await page.ScreenshotAsync("google.png");
GoToAsync
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 static async Task Main(string[] args)6 {7 {8 };9 using (var browser = await Puppeteer.LaunchAsync(options))10 {11 var page = await browser.NewPageAsync();12 }13 }14}15using System;16using System.Threading.Tasks;17using PuppeteerSharp;18{19 static async Task Main(string[] args)20 {21 {22 };23 using (var browser = await Puppeteer.LaunchAsync(options))24 {25 var page = await browser.NewPageAsync();26 }27 }28}29using System;30using System.Threading.Tasks;31using PuppeteerSharp;32{33 static async Task Main(string[] args)34 {35 {36 };37 using (var browser = await Puppeteer.LaunchAsync(options))38 {39 var page = await browser.NewPageAsync();40 }41 }42}43using System;44using System.Threading.Tasks;45using PuppeteerSharp;46{47 static async Task Main(string[] args)48 {49 {50 };51 using (var browser = await Puppeteer.LaunchAsync(options))52 {53 var page = await browser.NewPageAsync();54 }55 }56}57using System;58using System.Threading.Tasks;
GoToAsync
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4using System.IO;5{6 {7 static async Task Main(string[] args)8 {9 var browser = await Puppeteer.LaunchAsync(new LaunchOptions10 {11 Args = new string[] { "--no-sandbox", "--disable-setuid-sandbox" }12 });13 var page = await browser.NewPageAsync();14 await page.ScreenshotAsync("1.png");15 await browser.CloseAsync();16 }17 }18}19using System;20using System.Threading.Tasks;21using PuppeteerSharp;22using System.IO;23{24 {25 static async Task Main(string[] args)26 {27 var browser = await Puppeteer.LaunchAsync(new LaunchOptions28 {29 Args = new string[] { "--no-sandbox", "--disable-setuid-sandbox" }30 });31 var page = await browser.NewPageAsync();32 await page.ScreenshotAsync("2.png");33 await browser.CloseAsync();34 }35 }36}37using System;38using System.Threading.Tasks;39using PuppeteerSharp;40using System.IO;41{42 {43 static async Task Main(string[] args)44 {45 var browser = await Puppeteer.LaunchAsync(new LaunchOptions46 {47 Args = new string[] { "--no-sandbox", "--disable-setuid-sandbox" }48 });49 var page = await browser.NewPageAsync();50 await page.ScreenshotAsync("3.png");51 await browser.CloseAsync();52 }53 }54}55using System;
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!!