How to use WaitForSelectorAsync method of PuppeteerSharp.Frame class

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

FrameWaitForSelectorTests.cs

Source:FrameWaitForSelectorTests.cs Github

copy

Full Screen

...18 public async Task ShouldImmediatelyResolveTaskIfNodeExists()19 {20 await Page.GoToAsync(TestConstants.EmptyPage);21 var frame = Page.MainFrame;22 await frame.WaitForSelectorAsync("*");23 await frame.EvaluateFunctionAsync(AddElement, "div");24 await frame.WaitForSelectorAsync("div");25 }26 [PuppeteerTest("waittask.spec.ts", "Frame.waitForSelector", "should work with removed MutationObserver")]27 [SkipBrowserFact(skipFirefox: true)]28 public async Task ShouldWorkWithRemovedMutationObserver()29 {30 await Page.EvaluateExpressionAsync("delete window.MutationObserver");31 var waitForSelector = Page.WaitForSelectorAsync(".zombo");32 await Task.WhenAll(33 waitForSelector,34 Page.SetContentAsync("<div class='zombo'>anything</div>"));35 Assert.Equal("anything", await Page.EvaluateFunctionAsync<string>("x => x.textContent", await waitForSelector));36 }37 [PuppeteerTest("waittask.spec.ts", "Frame.waitForSelector", "should resolve promise when node is added")]38 [PuppeteerFact]39 public async Task ShouldResolveTaskWhenNodeIsAdded()40 {41 await Page.GoToAsync(TestConstants.EmptyPage);42 var frame = Page.MainFrame;43 var watchdog = frame.WaitForSelectorAsync("div");44 await frame.EvaluateFunctionAsync(AddElement, "br");45 await frame.EvaluateFunctionAsync(AddElement, "div");46 var eHandle = await watchdog;47 var property = await eHandle.GetPropertyAsync("tagName");48 var tagName = await property.JsonValueAsync<string>();49 Assert.Equal("DIV", tagName);50 }51 [PuppeteerTest("waittask.spec.ts", "Frame.waitForSelector", "should work when node is added through innerHTML")]52 [PuppeteerFact]53 public async Task ShouldWorkWhenNodeIsAddedThroughInnerHTML()54 {55 await Page.GoToAsync(TestConstants.EmptyPage);56 var watchdog = Page.WaitForSelectorAsync("h3 div");57 await Page.EvaluateFunctionAsync(AddElement, "span");58 await Page.EvaluateExpressionAsync("document.querySelector('span').innerHTML = '<h3><div></div></h3>'");59 await watchdog;60 }61 [PuppeteerTest("waittask.spec.ts", "Frame.waitForSelector", "Page.waitForSelector is shortcut for main frame")]62 [PuppeteerFact]63 public async Task PageWaitForSelectorAsyncIsShortcutForMainFrame()64 {65 await Page.GoToAsync(TestConstants.EmptyPage);66 await FrameUtils.AttachFrameAsync(Page, "frame1", TestConstants.EmptyPage);67 var otherFrame = Page.FirstChildFrame();68 var watchdog = Page.WaitForSelectorAsync("div");69 await otherFrame.EvaluateFunctionAsync(AddElement, "div");70 await Page.EvaluateFunctionAsync(AddElement, "div");71 var eHandle = await watchdog;72 Assert.Equal(Page.MainFrame, eHandle.ExecutionContext.Frame);73 }74 [PuppeteerTest("waittask.spec.ts", "Frame.waitForSelector", "should run in specified frame")]75 [PuppeteerFact]76 public async Task ShouldRunInSpecifiedFrame()77 {78 await FrameUtils.AttachFrameAsync(Page, "frame1", TestConstants.EmptyPage);79 await FrameUtils.AttachFrameAsync(Page, "frame2", TestConstants.EmptyPage);80 var frame1 = Page.FirstChildFrame();81 var frame2 = Page.Frames.ElementAt(2);82 var waitForSelectorPromise = frame2.WaitForSelectorAsync("div");83 await frame1.EvaluateFunctionAsync(AddElement, "div");84 await frame2.EvaluateFunctionAsync(AddElement, "div");85 var eHandle = await waitForSelectorPromise;86 Assert.Equal(frame2, eHandle.ExecutionContext.Frame);87 }88 [PuppeteerTest("waittask.spec.ts", "Frame.waitForSelector", "should throw when frame is detached")]89 [SkipBrowserFact(skipFirefox: true)]90 public async Task ShouldThrowWhenFrameIsDetached()91 {92 await FrameUtils.AttachFrameAsync(Page, "frame1", TestConstants.EmptyPage);93 var frame = Page.FirstChildFrame();94 var waitTask = frame.WaitForSelectorAsync(".box").ContinueWith(task => task?.Exception?.InnerException);95 await FrameUtils.DetachFrameAsync(Page, "frame1");96 var waitException = await waitTask;97 Assert.NotNull(waitException);98 Assert.Contains("waitForFunction failed: frame got detached.", waitException.Message);99 }100 [PuppeteerTest("waittask.spec.ts", "Frame.waitForSelector", "should survive cross-process navigation")]101 [PuppeteerFact]102 public async Task ShouldSurviveCrossProcessNavigation()103 {104 var boxFound = false;105 var waitForSelector = Page.WaitForSelectorAsync(".box").ContinueWith(_ => boxFound = true);106 await Page.GoToAsync(TestConstants.EmptyPage);107 Assert.False(boxFound);108 await Page.ReloadAsync();109 Assert.False(boxFound);110 await Page.GoToAsync(TestConstants.CrossProcessHttpPrefix + "/grid.html");111 await waitForSelector;112 Assert.True(boxFound);113 }114 [PuppeteerTest("waittask.spec.ts", "Frame.waitForSelector", "should wait for visible")]115 [PuppeteerFact]116 public async Task ShouldWaitForVisible()117 {118 var divFound = false;119 var waitForSelector = Page.WaitForSelectorAsync("div", new WaitForSelectorOptions { Visible = true })120 .ContinueWith(_ => divFound = true);121 await Page.SetContentAsync("<div style='display: none; visibility: hidden;'>1</div>");122 Assert.False(divFound);123 await Page.EvaluateExpressionAsync("document.querySelector('div').style.removeProperty('display')");124 Assert.False(divFound);125 await Page.EvaluateExpressionAsync("document.querySelector('div').style.removeProperty('visibility')");126 Assert.True(await waitForSelector);127 Assert.True(divFound);128 }129 [PuppeteerTest("waittask.spec.ts", "Frame.waitForSelector", "should wait for visible recursively")]130 [PuppeteerFact]131 public async Task ShouldWaitForVisibleRecursively()132 {133 var divVisible = false;134 var waitForSelector = Page.WaitForSelectorAsync("div#inner", new WaitForSelectorOptions { Visible = true })135 .ContinueWith(_ => divVisible = true);136 await Page.SetContentAsync("<div style='display: none; visibility: hidden;'><div id='inner'>hi</div></div>");137 Assert.False(divVisible);138 await Page.EvaluateExpressionAsync("document.querySelector('div').style.removeProperty('display')");139 Assert.False(divVisible);140 await Page.EvaluateExpressionAsync("document.querySelector('div').style.removeProperty('visibility')");141 Assert.True(await waitForSelector);142 Assert.True(divVisible);143 }144 [PuppeteerTest("waittask.spec.ts", "Frame.waitForSelector", "hidden should wait for visibility: hidden")]145 [PuppeteerTest("waittask.spec.ts", "Frame.waitForSelector", "hidden should wait for display: none")]146 [Theory]147 [InlineData("visibility", "hidden")]148 [InlineData("display", "none")]149 public async Task HiddenShouldWaitForVisibility(string propertyName, string propertyValue)150 {151 var divHidden = false;152 await Page.SetContentAsync("<div style='display: block;'></div>");153 var waitForSelector = Page.WaitForSelectorAsync("div", new WaitForSelectorOptions { Hidden = true })154 .ContinueWith(_ => divHidden = true);155 await Page.WaitForSelectorAsync("div"); // do a round trip156 Assert.False(divHidden);157 await Page.EvaluateExpressionAsync($"document.querySelector('div').style.setProperty('{propertyName}', '{propertyValue}')");158 Assert.True(await waitForSelector);159 Assert.True(divHidden);160 }161 [PuppeteerTest("waittask.spec.ts", "Frame.waitForSelector", "hidden should wait for removal")]162 [PuppeteerFact]163 public async Task HiddenShouldWaitForRemoval()164 {165 await Page.SetContentAsync("<div></div>");166 var divRemoved = false;167 var waitForSelector = Page.WaitForSelectorAsync("div", new WaitForSelectorOptions { Hidden = true })168 .ContinueWith(_ => divRemoved = true);169 await Page.WaitForSelectorAsync("div"); // do a round trip170 Assert.False(divRemoved);171 await Page.EvaluateExpressionAsync("document.querySelector('div').remove()");172 Assert.True(await waitForSelector);173 Assert.True(divRemoved);174 }175 [PuppeteerTest("waittask.spec.ts", "Frame.waitForSelector", "should return null if waiting to hide non-existing element")]176 [PuppeteerFact]177 public async Task ShouldReturnNullIfWaitingToHideNonExistingElement()178 {179 var handle = await Page.WaitForSelectorAsync("non-existing", new WaitForSelectorOptions { Hidden = true });180 Assert.Null(handle);181 }182 [PuppeteerTest("waittask.spec.ts", "Frame.waitForSelector", "should respect timeout")]183 [PuppeteerFact]184 public async Task ShouldRespectTimeout()185 {186 var exception = await Assert.ThrowsAsync<WaitTaskTimeoutException>(async ()187 => await Page.WaitForSelectorAsync("div", new WaitForSelectorOptions { Timeout = 10 }));188 Assert.Contains("waiting for selector 'div' failed: timeout", exception.Message);189 }190 [PuppeteerTest("waittask.spec.ts", "Frame.waitForSelector", "should have an error message specifically for awaiting an element to be hidden")]191 [PuppeteerFact]192 public async Task ShouldHaveAnErrorMessageSpecificallyForAwaitingAnElementToBeHidden()193 {194 await Page.SetContentAsync("<div></div>");195 var exception = await Assert.ThrowsAsync<WaitTaskTimeoutException>(async ()196 => await Page.WaitForSelectorAsync("div", new WaitForSelectorOptions { Hidden = true, Timeout = 10 }));197 Assert.Contains("waiting for selector 'div' to be hidden failed: timeout", exception.Message);198 }199 [PuppeteerTest("waittask.spec.ts", "Frame.waitForSelector", "should respond to node attribute mutation")]200 [PuppeteerFact]201 public async Task ShouldRespondToNodeAttributeMutation()202 {203 var divFound = false;204 var waitForSelector = Page.WaitForSelectorAsync(".zombo").ContinueWith(_ => divFound = true);205 await Page.SetContentAsync("<div class='notZombo'></div>");206 Assert.False(divFound);207 await Page.EvaluateExpressionAsync("document.querySelector('div').className = 'zombo'");208 Assert.True(await waitForSelector);209 }210 [PuppeteerTest("waittask.spec.ts", "Frame.waitForSelector", "should return the element handle")]211 [PuppeteerFact]212 public async Task ShouldReturnTheElementHandle()213 {214 var waitForSelector = Page.WaitForSelectorAsync(".zombo");215 await Page.SetContentAsync("<div class='zombo'>anything</div>");216 Assert.Equal("anything", await Page.EvaluateFunctionAsync<string>("x => x.textContent", await waitForSelector));217 }218 [PuppeteerTest("waittask.spec.ts", "Frame.waitForSelector", "should have correct stack trace for timeout")]219 [PuppeteerFact]220 public async Task ShouldHaveCorrectStackTraceForTimeout()221 {222 var exception = await Assert.ThrowsAsync<WaitTaskTimeoutException>(async ()223 => await Page.WaitForSelectorAsync(".zombo", new WaitForSelectorOptions { Timeout = 10 }));224 Assert.Contains("WaitForSelectorTests", exception.StackTrace);225 }226 }227}...

Full Screen

Full Screen

PuppeteerMethods.cs

Source:PuppeteerMethods.cs Github

copy

Full Screen

...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']");239 await page.EvaluateExpressionAsync("document.querySelector(\"input[name='btnK']\").click()");240 await page.WaitForNavigationAsync(new NavigationOptions { WaitUntil = waitUntil });241 }242 }243}...

Full Screen

Full Screen

Authorization.cs

Source:Authorization.cs Github

copy

Full Screen

...57 WaitForSelectorOptions WaitForSelectorTimeout = new WaitForSelectorOptions { Timeout = DefaultTimeout };58 Log.Information($"DefaultTimeout: {p.DefaultTimeout}");59 Log.Information($"DefaultNavigationTimeout: {p.DefaultNavigationTimeout}");60 const string button = "body > app-root > n3-grid > app-login > div > div.notice > div > app-login-form > div > button";61 await p.WaitForSelectorAsync(button, WaitForSelectorTimeout);62 await System.Threading.Tasks.Task.Delay(10000);63 await p.ClickAsync(button);64 Log.Information("Первый клик {Button}: успешно!", "Войти с ЕСИА");65 Log.Information($"{timer.ElapsedMilliseconds}");66 timer.Restart();67 p = await GetPage(browser, "https://esia.gosuslugi.ru");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);92 do93 {94 if (count > attempts) throw new Exception("Cookie X-JMT-Token is not present.");95 await System.Threading.Tasks.Task.Delay(1000);...

Full Screen

Full Screen

WaitForSelectorTests.cs

Source:WaitForSelectorTests.cs Github

copy

Full Screen

...16 {17 await Page.GoToAsync(TestConstants.EmptyPage);18 var frame = Page.MainFrame;19 var added = false;20 await frame.WaitForSelectorAsync("*").ContinueWith(_ => added = true);21 Assert.True(added);22 added = false;23 await frame.EvaluateFunctionAsync(AddElement, "div");24 await frame.WaitForSelectorAsync("div").ContinueWith(_ => added = true);25 Assert.True(added);26 }27 [Fact]28 public async Task ShouldResolveTaskWhenNodeIsAdded()29 {30 await Page.GoToAsync(TestConstants.EmptyPage);31 var frame = Page.MainFrame;32 var added = false;33 var watchdog = frame.WaitForSelectorAsync("div").ContinueWith(_ => added = true);34 // run nop function..35 await frame.EvaluateExpressionAsync("42");36 // .. to be sure that waitForSelector promise is not resolved yet.37 Assert.False(added);38 await frame.EvaluateFunctionAsync(AddElement, "br");39 Assert.False(added);40 await frame.EvaluateFunctionAsync(AddElement, "div");41 await watchdog;42 Assert.True(added);43 }44 [Fact]45 public async Task ShouldWorkWhenNodeIsAddedThroughInnerHTML()46 {47 await Page.GoToAsync(TestConstants.EmptyPage);48 var watchdog = Page.WaitForSelectorAsync("h3 div");49 await Page.EvaluateFunctionAsync(AddElement, "span");50 await Page.EvaluateExpressionAsync("document.querySelector('span').innerHTML = '<h3><div></div></h3>'");51 await watchdog;52 }53 [Fact]54 public async Task PageWaitForSelectorAsyncIsShortcutForMainFrame()55 {56 await Page.GoToAsync(TestConstants.EmptyPage);57 await FrameUtils.AttachFrameAsync(Page, "frame1", TestConstants.EmptyPage);58 var otherFrame = Page.Frames.ElementAt(1);59 var added = false;60 var waitForSelectorTask = Page.WaitForSelectorAsync("div").ContinueWith(_ => added = true);61 await otherFrame.EvaluateFunctionAsync(AddElement, "div");62 Assert.False(added);63 await Page.EvaluateFunctionAsync(AddElement, "div");64 Assert.True(await waitForSelectorTask);65 Assert.True(added);66 }67 [Fact]68 public async Task ShouldRunInSpecifiedFrame()69 {70 await FrameUtils.AttachFrameAsync(Page, "frame1", TestConstants.EmptyPage);71 await FrameUtils.AttachFrameAsync(Page, "frame2", TestConstants.EmptyPage);72 var frame1 = Page.Frames.ElementAt(1);73 var frame2 = Page.Frames.ElementAt(2);74 var added = false;75 var selectorTask = frame2.WaitForSelectorAsync("div").ContinueWith(_ => added = true);76 Assert.False(added);77 await frame1.EvaluateFunctionAsync(AddElement, "div");78 Assert.False(added);79 await frame2.EvaluateFunctionAsync(AddElement, "div");80 Assert.True(added);81 }82 [Fact]83 public async Task ShouldThrowIfEvaluationFailed()84 {85 await Page.EvaluateOnNewDocumentAsync(@"function() {86 document.querySelector = null;87 }");88 await Page.GoToAsync(TestConstants.EmptyPage);89 var exception = await Assert.ThrowsAnyAsync<PuppeteerException>(() => Page.WaitForSelectorAsync("*"));90 Assert.Contains("document.querySelector is not a function", exception.Message);91 }92 [Fact]93 public async Task ShouldThrowWhenFrameIsDetached()94 {95 await FrameUtils.AttachFrameAsync(Page, "frame1", TestConstants.EmptyPage);96 var frame = Page.Frames.ElementAt(1);97 var waitTask = frame.WaitForSelectorAsync(".box").ContinueWith(task => task?.Exception?.InnerException);98 await FrameUtils.DetachFrameAsync(Page, "frame1");99 var waitException = await waitTask;100 Assert.NotNull(waitException);101 Assert.Contains("waitForSelector failed: frame got detached", waitException.Message);102 }103 [Fact]104 public async Task ShouldSurviveCrossProcessNavigation()105 {106 var boxFound = false;107 var waitForSelector = Page.WaitForSelectorAsync(".box").ContinueWith(_ => boxFound = true);108 await Page.GoToAsync(TestConstants.EmptyPage);109 Assert.False(boxFound);110 await Page.ReloadAsync();111 Assert.False(boxFound);112 await Page.GoToAsync(TestConstants.CrossProcessHttpPrefix + "/grid.html");113 await waitForSelector;114 Assert.True(boxFound);115 }116 [Fact]117 public async Task ShouldWaitForVisible()118 {119 var divFound = false;120 var waitForSelector = Page.WaitForSelectorAsync("div", new WaitForSelectorOptions { Visible = true })121 .ContinueWith(_ => divFound = true);122 await Page.SetContentAsync("<div style='display: none; visibility: hidden;'>1</div>");123 Assert.False(divFound);124 await Page.EvaluateExpressionAsync("document.querySelector('div').style.removeProperty('display')");125 Assert.False(divFound);126 await Page.EvaluateExpressionAsync("document.querySelector('div').style.removeProperty('visibility')");127 Assert.True(await waitForSelector);128 Assert.True(divFound);129 }130 [Fact]131 public async Task ShouldWaitForVisibleRecursively()132 {133 var divVisible = false;134 var waitForSelector = Page.WaitForSelectorAsync("div#inner", new WaitForSelectorOptions { Visible = true })135 .ContinueWith(_ => divVisible = true);136 await Page.SetContentAsync("<div style='display: none; visibility: hidden;'><div id='inner'>hi</div></div>");137 Assert.False(divVisible);138 await Page.EvaluateExpressionAsync("document.querySelector('div').style.removeProperty('display')");139 Assert.False(divVisible);140 await Page.EvaluateExpressionAsync("document.querySelector('div').style.removeProperty('visibility')");141 Assert.True(await waitForSelector);142 Assert.True(divVisible);143 }144 [Theory]145 [InlineData("visibility", "hidden")]146 [InlineData("display", "none")]147 public async Task HiddenShouldWaitForVisibility(string propertyName, string propertyValue)148 {149 var divHidden = false;150 await Page.SetContentAsync("<div style='display: block;'></div>");151 var waitForSelector = Page.WaitForSelectorAsync("div", new WaitForSelectorOptions { Hidden = true })152 .ContinueWith(_ => divHidden = true);153 await Page.WaitForSelectorAsync("div"); // do a round trip154 Assert.False(divHidden);155 await Page.EvaluateExpressionAsync($"document.querySelector('div').style.setProperty('{propertyName}', '{propertyValue}')");156 Assert.True(await waitForSelector);157 Assert.True(divHidden);158 }159 [Fact]160 public async Task HiddenShouldWaitForRemoval()161 {162 await Page.SetContentAsync("<div></div>");163 var divRemoved = false;164 var waitForSelector = Page.WaitForSelectorAsync("div", new WaitForSelectorOptions { Hidden = true })165 .ContinueWith(_ => divRemoved = true);166 await Page.WaitForSelectorAsync("div"); // do a round trip167 Assert.False(divRemoved);168 await Page.EvaluateExpressionAsync("document.querySelector('div').remove()");169 Assert.True(await waitForSelector);170 Assert.True(divRemoved);171 }172 [Fact]173 public async Task ShouldRespectTimeout()174 {175 var exception = await Assert.ThrowsAnyAsync<PuppeteerException>(async ()176 => await Page.WaitForSelectorAsync("div", new WaitForSelectorOptions { Timeout = 10 }));177 Assert.NotNull(exception);178 Assert.Contains("waiting failed: timeout", exception.Message);179 }180 [Fact]181 public async Task ShouldRespondToNodeAttributeMutation()182 {183 var divFound = false;184 var waitForSelector = Page.WaitForSelectorAsync(".zombo").ContinueWith(_ => divFound = true);185 await Page.SetContentAsync("<div class='notZombo'></div>");186 Assert.False(divFound);187 await Page.EvaluateExpressionAsync("document.querySelector('div').className = 'zombo'");188 Assert.True(await waitForSelector);189 }190 [Fact]191 public async Task ShouldReturnTheElementHandle()192 {193 var waitForSelector = Page.WaitForSelectorAsync(".zombo");194 await Page.SetContentAsync("<div class='zombo'>anything</div>");195 Assert.Equal("anything", await Page.EvaluateFunctionAsync<string>("x => x.textContent", await waitForSelector));196 }197 }198}...

Full Screen

Full Screen

Robot.cs

Source:Robot.cs Github

copy

Full Screen

...85 OnMessage("登录");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}...

Full Screen

Full Screen

Clean163Email.cs

Source:Clean163Email.cs Github

copy

Full Screen

...19 {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");...

Full Screen

Full Screen

PuppeteerExtensions.cs

Source:PuppeteerExtensions.cs Github

copy

Full Screen

...8 {9 ElementHandle element = null;10 try11 {12 element = await frame.WaitForSelectorAsync(cssSelector, new WaitForSelectorOptions13 {14 Timeout = 100015 });16 }17 catch (System.Exception)18 {19 return null;20 }21 return await frame.GetInnerText(element);22 }23 public static async Task<string> GetInnerText(this Frame frame, ElementHandle handle)24 {25 return await frame.EvaluateFunctionAsync<string>("el => el.textContent", handle);26 }...

Full Screen

Full Screen

WaitForSelectorOptions.cs

Source:WaitForSelectorOptions.cs Github

copy

Full Screen

2{3 /// <summary>4 /// Optional waiting parameters.5 /// </summary>6 /// <seealso cref="Page.WaitForSelectorAsync(string, WaitForSelectorOptions)"/>7 /// <seealso cref="Frame.WaitForSelectorAsync(string, WaitForSelectorOptions)"/>8 public class WaitForSelectorOptions9 {10 /// <summary>11 /// Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). 12 /// Pass `0` to disable timeout. 13 /// The default value can be changed by using <seealso cref="Page.DefaultTimeout"/> method14 /// </summary>15 public int? Timeout { get; set; }16 /// <summary>17 /// Wait for element to be present in DOM and to be visible.18 /// </summary>19 public bool Visible { get; set; }20 /// <summary>21 /// Wait for element to not be found in the DOM or to be hidden....

Full Screen

Full Screen

WaitForSelectorAsync

Using AI Code Generation

copy

Full Screen

1using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true }))2{3 var page = await browser.NewPageAsync();4 await page.WaitForSelectorAsync("input[name='q']");5 await page.TypeAsync("input[name='q']", "PuppeteerSharp");6 await page.ClickAsync("input[name='btnK']");7 await page.WaitForNavigationAsync();8 Console.WriteLine(await page.GetContentAsync());9}10using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true }))11{12 var page = await browser.NewPageAsync();13 await page.EvaluateExpressionAsync("() => console.log(`url is ${location.href}`)");14}15using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true }))16{17 var page = await browser.NewPageAsync();18 await page.ScreenshotAsync("screenshot.png");19}20using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true }))21{22 var page = await browser.NewPageAsync();23 var title = await page.GetTitleAsync();24 Console.WriteLine(title);25}26using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true }))27{28 var page = await browser.NewPageAsync();29 var content = await page.GetContentAsync();30 Console.WriteLine(content);31}32using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true }))33{34 var page = await browser.NewPageAsync();35 var cookies = await page.GetCookiesAsync();36 foreach (var cookie in cookies)37 {38 Console.WriteLine(cookie);39 }40}

Full Screen

Full Screen

WaitForSelectorAsync

Using AI Code Generation

copy

Full Screen

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.WaitForSelectorAsync("input[name=q]");12 await page.TypeAsync("input[name=q]", "PuppeteerSharp");13 await page.ClickAsync("input[name=btnK]");14 await page.WaitForNavigationAsync();15 await page.ScreenshotAsync("screenshot.png");16 await browser.CloseAsync();17 }18 }19}

Full Screen

Full Screen

WaitForSelectorAsync

Using AI Code Generation

copy

Full Screen

1var browser = await Puppeteer.LaunchAsync(new LaunchOptions2{3 Args = new string[] { "--no-sandbox" }4});5var page = await browser.NewPageAsync();6await page.GoToAsync(url);7await page.WaitForSelectorAsync(".gb_P");8var browser = await Puppeteer.LaunchAsync(new LaunchOptions9{10 Args = new string[] { "--no-sandbox" }11});12var page = await browser.NewPageAsync();13await page.GoToAsync(url);14await page.WaitForSelectorAsync(".gb_P");15var browser = await Puppeteer.LaunchAsync(new LaunchOptions16{17 Args = new string[] { "--no-sandbox" }18});19var page = await browser.NewPageAsync();20await page.GoToAsync(url);21await page.MainFrame.WaitForSelectorAsync(".gb_P");22var browser = await Puppeteer.LaunchAsync(new LaunchOptions23{24 Args = new string[] { "--no-sandbox" }25});26var page = await browser.NewPageAsync();27await page.GoToAsync(url);28await page.MainFrame.WaitForSelectorAsync(".gb_P");

Full Screen

Full Screen

WaitForSelectorAsync

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static void Main(string[] args)7 {8 var task = MainAsync();9 task.Wait();10 }11 static async Task MainAsync()12 {13 {14 };15 var browser = await Puppeteer.LaunchAsync(options);16 var page = await browser.NewPageAsync();17 var selector = await page.WaitForSelectorAsync("input[name='q']", new WaitForSelectorOptions { Timeout = 10000 });18 await selector.TypeAsync("Puppeteer");19 await selector.PressAsync("Enter");20 var selector2 = await page.WaitForSelectorAsync("h3", new WaitForSelectorOptions { Timeout = 10000 });21 await selector2.ClickAsync();22 await selector3.ClickAsync();23 await Task.Delay(5000);24 await browser.CloseAsync();25 }26 }27}

Full Screen

Full Screen

WaitForSelectorAsync

Using AI Code Generation

copy

Full Screen

1var page = await browser.NewPageAsync();2var searchBox = await page.WaitForSelectorAsync("input[title='Search']");3await searchBox.TypeAsync("PuppeteerSharp");4await page.Keyboard.PressAsync("Enter");5await page.ScreenshotAsync("result.png");6var page = await browser.NewPageAsync();7await searchBox.TypeAsync("PuppeteerSharp");8await page.Keyboard.PressAsync("Enter");9await page.ScreenshotAsync("result.png");10var page = await browser.NewPageAsync();11await page.WaitForFunctionAsync("document.querySelector('input[title=\"Search\"]').value == 'PuppeteerSharp'");12var searchBox = await page.QuerySelectorAsync("input[title='Search']");13await searchBox.TypeAsync("PuppeteerSharp");14await page.Keyboard.PressAsync("Enter");15await page.ScreenshotAsync("result.png");16var page = await browser.NewPageAsync();17await page.WaitForTimeoutAsync(1000);18var searchBox = await page.QuerySelectorAsync("input[title='Search']");19await searchBox.TypeAsync("PuppeteerSharp");20await page.Keyboard.PressAsync("Enter");21await page.ScreenshotAsync("result.png");22var page = await browser.NewPageAsync();23var searchBox = await page.QuerySelectorAsync("input[title='Search']");24await searchBox.TypeAsync("PuppeteerSharp");

Full Screen

Full Screen

WaitForSelectorAsync

Using AI Code Generation

copy

Full Screen

1using PuppeteerSharp;2{3 static void Main(string[] args)4 {5 WaitForSelectorAsync().Wait();6 }7 static async Task WaitForSelectorAsync()8 {9 var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false });10 var page = await browser.NewPageAsync();11 await page.WaitForSelectorAsync("input[name='q']");12 await browser.CloseAsync();13 }14}15using PuppeteerSharp;16{17 static void Main(string[] args)18 {19 WaitForSelectorAsync().Wait();20 }21 static async Task WaitForSelectorAsync()22 {23 var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false });24 var page = await browser.NewPageAsync();25 await page.WaitForSelectorAsync("input[name='q']", new WaitForSelectorOptions { Visible = true });26 await browser.CloseAsync();27 }28}29using PuppeteerSharp;30{31 static void Main(string[] args)32 {33 WaitForSelectorAsync().Wait();34 }35 static async Task WaitForSelectorAsync()36 {37 var browser = await Puppeteer.LaunchAsync(new LaunchOptions {

Full Screen

Full Screen

WaitForSelectorAsync

Using AI Code Generation

copy

Full Screen

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 LaunchOptions10 {11 Args = new string[] { "--no-sandbox" }12 }))13 {14 using (var page = await browser.NewPageAsync())15 {16 var element = await page.WaitForSelectorAsync("#tsf > div:nth-child(2) > div > div.RNNXgb > div > div.a4bIc > input");17 var result = await element.ClickAsync();18 Console.WriteLine(result);19 }20 }21 }22 }23}24using System;25using System.Threading.Tasks;26using PuppeteerSharp;27{28 {29 static async Task Main(string[] args)30 {31 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);32 using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions33 {34 Args = new string[] { "--no-sandbox" }35 }))36 {37 using (var page = await browser.NewPageAsync())38 {

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful