How to use QuerySelectorAllAsync method of PuppeteerSharp.Frame class

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

Program.cs

Source:Program.cs Github

copy

Full Screen

...198 AnsiConsole.WriteLine("模拟按下Enter键盘");199 await page.Keyboard.PressAsync("Enter");200 await page.WaitForNavigationAsync(); //注意 如果导航发生了变化 必须使用等待导航201 var Content = await page.GetContentAsync(); //获取页面内容202 var yuRUbf = await page.QuerySelectorAllAsync("div[class='yuRUbf']"); //获取class为yuRUbf所有div203 AnsiConsole.WriteLine($"获取到前:{yuRUbf.Length}条搜索数据\n");204 foreach (var item in yuRUbf)205 {206 var Tittle = await item.QuerySelectorAllAsync(@"a>h3");207 var Url = await item.QuerySelectorAllAsync(@"a");208 var StrTittle = await Tittle[0].GetPropertyAsync("innerText");209 var StrUrl = await Url[0].GetPropertyAsync("href");210 AnsiConsole.WriteLine($"标题:{StrTittle.ToString().Replace("JSHandle:", "")}\n地址:{StrUrl.ToString().Replace("JSHandle:", "")}\n\n");211 }212 AnsiConsole.WriteLine("等待三秒");213 await page.WaitForTimeoutAsync(3000);214 AnsiConsole.WriteLine("结束");215 };216 };217 return true;218 }219 /// <summary>220 /// 国开多课程简单看视频看文章221 /// </summary>222 /// <returns></returns>223 public static async void Ouchn()224 {225 var CourseList = new Dictionary<string, Page>();226 var Task = new List<Task>();227 var Pages = await browser.PagesAsync(); //获取当前所有page228 Console.WriteLine($"请按照教程来,要关闭所有的Edge界面");229 Console.WriteLine($"课程结束请输入exit退出课程,在课程未完成时也可以输入exit退出");230 Console.WriteLine($"课程结束请输入exit退出课程,在课程未完成时也可以输入exit退出");231 Console.WriteLine($"课程结束请输入exit退出课程,在课程未完成时也可以输入exit退出");232 Thread.Sleep(1000 * 5);233 Console.WriteLine($"获取到当前浏览器页面有:{Pages.Length}个");234 if (Pages.Length > 0)235 {236 Console.WriteLine("开始匹配所有链接是否为国开课程页面...");237 for (int i = 0; i < Pages.Length; i++)238 {239 var Page = Pages[i];240 var Url = Page.Url.ToString();241 var Name = await Page.GetTitleAsync();242 if (Regex.IsMatch(Url, @"http://([\w-]+\.)+[\w-]+(/[\w-./?%&=]*)?id=[0-9]*"))243 {244 Console.WriteLine($"匹配成功:({Name}){Url}");245 CourseList.Add(Name, Page);246 }247 }248 if (CourseList.Count > 0)249 {250 Console.WriteLine($"匹配到符合国开课程页面总数:{CourseList.Count}个");251 }252 else253 {254 Console.WriteLine($"没有匹配到符合国开课程页面,请输入任意键退出...");255 Console.ReadLine();256 }257 }258 else259 {260 Console.WriteLine($"当前获取到页面为0,请输入任意键退出...");261 Console.ReadLine();262 }263 Console.WriteLine($"\n开始创建线程...");264 foreach (var item in CourseList)265 {266 var Tas = new System.Threading.Tasks.Task(async () =>267 {268 var Links = await item.Value.QuerySelectorAllAsync("a[class='aalink']"); //获取第一个页面的所有a标签class为aalink的269 Console.WriteLine($"[课程:{item.Key}]获取到{Links.Length}个链接");270 async Task<bool> OpenLink(ElementHandle[] handles)271 {272 try273 {274 var r = new Random();275 for (int i = 0; i < Links.Length; i++)276 {277 var URL = await Links[i].GetPropertyAsync("href");278 if (URL.ToString().Replace("JSHandle:", "").Contains(""))279 {280 }281 var Page = await browser.NewPageAsync();282 await Page.GoToAsync(URL.ToString().Replace("JSHandle:", ""), new NavigationOptions() { });...

Full Screen

Full Screen

DOMWorld.cs

Source:DOMWorld.cs Github

copy

Full Screen

...93 var document = await GetDocument().ConfigureAwait(false);94 var value = await document.QuerySelectorAsync(selector).ConfigureAwait(false);95 return value;96 }97 internal async Task<ElementHandle[]> QuerySelectorAllAsync(string selector)98 {99 var document = await GetDocument().ConfigureAwait(false);100 var value = await document.QuerySelectorAllAsync(selector).ConfigureAwait(false);101 return value;102 }103 internal async Task<ElementHandle[]> XPathAsync(string expression)104 {105 var document = await GetDocument().ConfigureAwait(false);106 var value = await document.XPathAsync(expression).ConfigureAwait(false);107 return value;108 }109 internal Task<string> GetContentAsync() => EvaluateFunctionAsync<string>(@"() => {110 let retVal = '';111 if (document.doctype)112 retVal = new XMLSerializer().serializeToString(document.doctype);113 if (document.documentElement)114 retVal += document.documentElement.outerHTML;...

Full Screen

Full Screen

Methods.cs

Source:Methods.cs Github

copy

Full Screen

...29 string text, int timeBetweenKeystrokes = 0)30 {31 data.Logger.LogHeader();32 var frame = GetFrame(data);33 var elem = (await frame.QuerySelectorAllAsync(BuildSelector(findBy, identifier)))[index];34 await elem.TypeAsync(text, new PuppeteerSharp.Input.TypeOptions { Delay = timeBetweenKeystrokes });35 data.Logger.Log($"Typed {text}", LogColors.DarkSalmon);36 }37 [Block("Types text in an input field with human-like random delays", name = "Type Human")]38 public static async Task PuppeteerTypeElementHuman(BotData data, FindElementBy findBy, string identifier, int index,39 string text)40 {41 data.Logger.LogHeader();42 var frame = GetFrame(data);43 var elem = (await frame.QuerySelectorAllAsync(BuildSelector(findBy, identifier)))[index];44 foreach (var c in text)45 {46 await elem.TypeAsync(c.ToString());47 await Task.Delay(data.Random.Next(100, 300)); // Wait between 100 and 300 ms (average human type speed is 60 WPM ~ 360 CPM)48 }49 data.Logger.Log($"Typed {text}", LogColors.DarkSalmon);50 }51 [Block("Clicks an element", name = "Click")]52 public static async Task PuppeteerClick(BotData data, FindElementBy findBy, string identifier, int index,53 PuppeteerSharp.Input.MouseButton mouseButton = PuppeteerSharp.Input.MouseButton.Left, int clickCount = 1,54 int timeBetweenClicks = 0)55 {56 data.Logger.LogHeader();57 var frame = GetFrame(data);58 var elem = (await frame.QuerySelectorAllAsync(BuildSelector(findBy, identifier)))[index];59 await elem.ClickAsync(new PuppeteerSharp.Input.ClickOptions { Button = mouseButton, ClickCount = clickCount, Delay = timeBetweenClicks });60 data.Logger.Log($"Clicked {clickCount} time(s) with {mouseButton} button", LogColors.DarkSalmon);61 }62 [Block("Submits a form", name = "Submit")]63 public static async Task PuppeteerSubmit(BotData data, FindElementBy findBy, string identifier, int index)64 {65 data.Logger.LogHeader();66 var elemScript = GetElementScript(findBy, identifier, index);67 var frame = GetFrame(data);68 var script = elemScript + ".submit();";69 await frame.EvaluateExpressionAsync(script);70 data.Logger.Log($"Submitted the form by executing {script}", LogColors.DarkSalmon);71 }72 [Block("Selects a value in a select element", name = "Select")]73 public static async Task PuppeteerSelect(BotData data, FindElementBy findBy, string identifier, int index, string value)74 {75 data.Logger.LogHeader();76 var frame = GetFrame(data);77 var elem = (await frame.QuerySelectorAllAsync(BuildSelector(findBy, identifier)))[index];78 await elem.SelectAsync(value);79 data.Logger.Log($"Selected value {value}", LogColors.DarkSalmon);80 }81 [Block("Gets the value of an attribute of an element", name = "Get Attribute Value")]82 public static async Task<string> PuppeteerGetAttributeValue(BotData data, FindElementBy findBy, string identifier, int index,83 string attributeName = "innerText")84 {85 data.Logger.LogHeader();86 var elemScript = GetElementScript(findBy, identifier, index);87 var frame = GetFrame(data);88 var script = $"{elemScript}.{attributeName};";89 var value = await frame.EvaluateExpressionAsync<string>(script);90 data.Logger.Log($"Got value {value} of attribute {attributeName} by executing {script}", LogColors.DarkSalmon);91 return value;92 }93 [Block("Gets the values of an attribute of multiple elements", name = "Get Attribute Value All")]94 public static async Task<List<string>> PuppeteerGetAttributeValueAll(BotData data, FindElementBy findBy, string identifier,95 string attributeName = "innerText")96 {97 data.Logger.LogHeader();98 var elemScript = GetElementsScript(findBy, identifier);99 var frame = GetFrame(data);100 var script = $"Array.prototype.slice.call({elemScript}).map((item) => item.{attributeName})";101 var values = await frame.EvaluateExpressionAsync<string[]>(script);102 data.Logger.Log($"Got {values.Length} values for attribute {attributeName} by executing {script}", LogColors.DarkSalmon);103 return values.ToList();104 }105 [Block("Checks if an element is currently being displayed on the page", name = "Is Displayed")]106 public static async Task<bool> PuppeteerIsDisplayed(BotData data, FindElementBy findBy, string identifier, int index)107 {108 data.Logger.LogHeader();109 var elemScript = GetElementScript(findBy, identifier, index);110 var frame = GetFrame(data);111 var script = $"window.getComputedStyle({elemScript}).display !== 'none';";112 var displayed = await frame.EvaluateExpressionAsync<bool>(script);113 data.Logger.Log($"Found out the element is{(displayed ? "" : " not")} displayed by executing {script}", LogColors.DarkSalmon);114 return displayed;115 }116 [Block("Uploads a file to the selected element", name = "Upload File")]117 public static async Task PuppeteerUploadFile(BotData data, FindElementBy findBy, string identifier, int index, string filePath)118 {119 data.Logger.LogHeader();120 var frame = GetFrame(data);121 var elem = (await frame.QuerySelectorAllAsync(BuildSelector(findBy, identifier)))[index];122 await elem.UploadFileAsync(filePath);123 data.Logger.Log($"Uploaded {filePath} to the element", LogColors.DarkSalmon);124 }125 [Block("Gets the X coordinate of the element in pixels", name = "Get Position X")]126 public static async Task<int> PuppeteerGetPositionX(BotData data, FindElementBy findBy, string identifier, int index)127 {128 data.Logger.LogHeader();129 var frame = GetFrame(data);130 var elem = (await frame.QuerySelectorAllAsync(BuildSelector(findBy, identifier)))[index];131 var x = (int)(await elem.BoundingBoxAsync()).X;132 data.Logger.Log($"The X coordinate of the element is {x}", LogColors.DarkSalmon);133 return x;134 }135 [Block("Gets the Y coordinate of the element in pixels", name = "Get Position Y")]136 public static async Task<int> PuppeteerGetPositionY(BotData data, FindElementBy findBy, string identifier, int index)137 {138 data.Logger.LogHeader();139 var frame = GetFrame(data);140 var elem = (await frame.QuerySelectorAllAsync(BuildSelector(findBy, identifier)))[index];141 var y = (int)(await elem.BoundingBoxAsync()).Y;142 data.Logger.Log($"The Y coordinate of the element is {y}", LogColors.DarkSalmon);143 return y;144 }145 [Block("Gets the width of the element in pixels", name = "Get Width")]146 public static async Task<int> PuppeteerGetWidth(BotData data, FindElementBy findBy, string identifier, int index)147 {148 data.Logger.LogHeader();149 var frame = GetFrame(data);150 var elem = (await frame.QuerySelectorAllAsync(BuildSelector(findBy, identifier)))[index];151 var width = (int)(await elem.BoundingBoxAsync()).Width;152 data.Logger.Log($"The width of the element is {width}", LogColors.DarkSalmon);153 return width;154 }155 [Block("Gets the height of the element in pixels", name = "Get Height")]156 public static async Task<int> PuppeteerGetHeight(BotData data, FindElementBy findBy, string identifier, int index)157 {158 data.Logger.LogHeader();159 var frame = GetFrame(data);160 var elem = (await frame.QuerySelectorAllAsync(BuildSelector(findBy, identifier)))[index];161 var height = (int)(await elem.BoundingBoxAsync()).Height;162 data.Logger.Log($"The height of the element is {height}", LogColors.DarkSalmon);163 return height;164 }165 [Block("Takes a screenshot of the element and saves it to an output file", name = "Screenshot Element")]166 public static async Task PuppeteerScreenshotElement(BotData data, FindElementBy findBy, string identifier, int index,167 string fileName, bool fullPage = false, bool omitBackground = false)168 {169 data.Logger.LogHeader();170 if (data.Providers.Security.RestrictBlocksToCWD)171 FileUtils.ThrowIfNotInCWD(fileName);172 var frame = GetFrame(data);173 var elem = (await frame.QuerySelectorAllAsync(BuildSelector(findBy, identifier)))[index];174 await elem.ScreenshotAsync(fileName, new PuppeteerSharp.ScreenshotOptions { FullPage = fullPage, OmitBackground = omitBackground });175 data.Logger.Log($"Took a screenshot of the element and saved it to {fileName}", LogColors.DarkSalmon);176 }177 [Block("Takes a screenshot of the element and converts it to a base64 string", name = "Screenshot Element Base64")]178 public static async Task<string> PuppeteerScreenshotBase64(BotData data, FindElementBy findBy, string identifier, int index,179 bool fullPage = false, bool omitBackground = false)180 {181 data.Logger.LogHeader();182 var frame = GetFrame(data);183 var elem = (await frame.QuerySelectorAllAsync(BuildSelector(findBy, identifier)))[index];184 var base64 = await elem.ScreenshotBase64Async(new PuppeteerSharp.ScreenshotOptions { FullPage = fullPage, OmitBackground = omitBackground });185 data.Logger.Log($"Took a screenshot of the element as base64", LogColors.DarkSalmon);186 return base64;187 }188 [Block("Switches to a different iframe", name = "Switch to Frame")]189 public static async Task PuppeteerSwitchToFrame(BotData data, FindElementBy findBy, string identifier, int index)190 {191 data.Logger.LogHeader();192 var frame = GetFrame(data);193 var elem = (await frame.QuerySelectorAllAsync(BuildSelector(findBy, identifier)))[index];194 data.Objects["puppeteerFrame"] = await elem.ContentFrameAsync();195 data.Logger.Log($"Switched to iframe", LogColors.DarkSalmon);196 }197 [Block("Waits for an element to appear on the page", name = "Wait for Element")]198 public static async Task PuppeteerWaitForElement(BotData data, FindElementBy findBy, string identifier, bool hidden = false, bool visible = true,199 int timeout = 30000)200 {201 data.Logger.LogHeader();202 var frame = GetFrame(data);203 await frame.WaitForSelectorAsync(BuildSelector(findBy, identifier),204 new PuppeteerSharp.WaitForSelectorOptions { Hidden = hidden, Visible = visible, Timeout = timeout });205 data.Logger.Log($"Waited for element with {findBy} {identifier}", LogColors.DarkSalmon);206 }207 private static string GetElementsScript(FindElementBy findBy, string identifier)...

Full Screen

Full Screen

ClickerBot.cs

Source:ClickerBot.cs Github

copy

Full Screen

...102 {103 var timeout = 1000;104 await frame.WaitForTimeoutAsync(timeout);105 await UpdateWrongQuizAnswers(frame);106 var highImportanceButtons = await frame.QuerySelectorAllAsync(".question-example-overlay:not([hidden='hidden']) .example-buttons .button:not(.is-disabled)");107 foreach (var buttonHandle in highImportanceButtons)108 {109 var boundingBox = await buttonHandle.BoundingBoxAsync();110 var isVisible = boundingBox != null && boundingBox.Width > 0 && boundingBox.Height > 0;111 if (!isVisible)112 continue;113 var buttonText = await frame.GetInnerText(buttonHandle);114 var isCandidate = new[] { "schließen" }.Any(x => buttonText.ToLower().Contains(x));115 if (isCandidate)116 return buttonHandle;117 }118 var decisionTextHandle = await frame.QuerySelectorAllAsync(".decision-wrapper .text-column");119 if (decisionTextHandle.Any())120 {121 var decisionText = await frame.EvaluateFunctionAsync<string>("el => el.innerText", decisionTextHandle.First());122 var decisionHash = decisionText.GetHashCode();123 var choices = await frame.QuerySelectorAllAsync(".content-region .decision-choices li.choice button:not(.is-disabled)");124 Question decision = null;125 if (_decisions.Questions.All(x => x.Hash != decisionHash))126 {127 decision = new Question { Hash = decisionHash };128 foreach (var elementHandle in choices)129 {130 var choiceText = await frame.GetInnerText(elementHandle);131 decision.Answers.Add(new Answer { Result = null, Text = choiceText });132 }133 _decisions.Questions.Add(decision);134 }135 else136 decision = _decisions.Questions.Single(x => x.Hash == decisionHash);137 var bestAnswer = decision.GetBestAnswer();138 if (bestAnswer != null)139 {140 foreach (var elementHandle in choices)141 {142 var boundingBox = await elementHandle.BoundingBoxAsync();143 var isVisible = boundingBox != null && boundingBox.Width > 0 && boundingBox.Height > 0;144 if (!isVisible)145 continue;146 var choiceText = await frame.EvaluateFunctionAsync<string>("e => e.innerText", elementHandle);147 if (choiceText == bestAnswer)148 return elementHandle;149 }150 }151 }152 var quizChoices = await frame.QuerySelectorAllAsync(".content-region .question-choices li.choice button:not(.is-disabled)");153 if (quizChoices.Any())154 {155 var contentHash = await GetQuizHash(frame);156 var bestAnswer = _quiz.Questions.Single(x => x.Hash == contentHash).GetBestAnswer();157 if (bestAnswer != null)158 {159 foreach (var elementHandle in quizChoices)160 {161 var boundingBox = await elementHandle.BoundingBoxAsync();162 var isVisible = boundingBox != null && boundingBox.Width > 0 && boundingBox.Height > 0;163 if (!isVisible)164 continue;165 var choiceText = await frame.GetInnerText(elementHandle);166 if (choiceText == bestAnswer)167 return elementHandle;168 }169 }170 }171 var regularButtons = await frame.QuerySelectorAllAsync(".content-region button.action:not(.is-disabled)");172 var exampleButtons = await frame.QuerySelectorAllAsync(".example-button-container .button:not(.is-disabled)");173 var buttonHandles = regularButtons.Concat(exampleButtons).Concat(highImportanceButtons);174 foreach (var buttonHandle in buttonHandles)175 {176 var boundingBox = await buttonHandle.BoundingBoxAsync();177 var isVisible = boundingBox != null && boundingBox.Width > 0 && boundingBox.Height > 0;178 if (!isVisible)179 continue;180 var buttonText = await frame.GetInnerText(buttonHandle);181 var isCandidate = new[] { "beginnen", "weiter", "mehr", "anzeigen", "schließen", "wiederholen" }.Any(x => buttonText.ToLower().Contains(x));182 if (isCandidate)183 return buttonHandle;184 }185 var currentCalloutHandles = await frame.QuerySelectorAllAsync(".callout-trigger.is-current");186 if (!currentCalloutHandles.Any())187 {188 var calloutHandles = await frame.QuerySelectorAllAsync(".callout-trigger.is-unlocked:not(.is-current)");189 if (calloutHandles.Any())190 return calloutHandles.First();191 }192 else193 {194 var next = await frame.QuerySelectorAllAsync(".callout-navigation.next a");195 if (next.Any())196 {197 var boundingBox = await next.First().BoundingBoxAsync();198 var isVisible = boundingBox != null && boundingBox.Width > 0 && boundingBox.Height > 0;199 if (isVisible)200 return next.First();201 }202 }203 var bannerHandles = await frame.QuerySelectorAllAsync(".banner-wrapper.is-unlocked");204 if (bannerHandles.Any())205 return bannerHandles.First();206 var explorerHandles = await frame.QuerySelectorAllAsync(".explorer-trigger.is-unlocked:not(.is-completed)");207 if (explorerHandles.Any())208 return explorerHandles.First();209 var flashCardHandles = await frame.QuerySelectorAllAsync(".content-region article.flash-card:not(.flash-card-flipped) .flash-card-side");210 if (flashCardHandles.Any())211 return flashCardHandles.First();212 return null;213 }214 private async Task<int> GetQuizHash(Frame frame)215 {216 var heading = await frame.TryGetTextContent(".content-heading") ?? "";217 var content = await frame.TryGetTextContent(".content_card") ?? "";218 return (heading + content).GetHashCode();219 }220 private async Task UpdateWrongQuizAnswers(Frame frame)221 {222 var quizChoices = await frame.QuerySelectorAllAsync(".content-region .question-choices li.choice button");223 if (quizChoices.Length > 0)224 {225 var contentHash = await GetQuizHash(frame);226 if (_quiz.Questions.All(x => x.Hash != contentHash))227 {228 var question = new Question() { Hash = contentHash };229 foreach (var elementHandle in quizChoices)230 {231 var choiceText = await frame.GetInnerText(elementHandle);232 question.Answers.Add(new Answer { Result = null, Text = choiceText });233 }234 235 _quiz.Questions.Add(question);236 //seems to be a new quiz, abort for now....

Full Screen

Full Screen

Form1.cs

Source:Form1.cs Github

copy

Full Screen

...216 //public async Task<ElementHandle[]> GetAllElement_ByCssSelector(string selector)217 //{218 // ElementHandle[] eles;219 // if (usingFrame)220 // eles = await frame.QuerySelectorAllAsync(selector);221 // else222 // eles = await page.QuerySelectorAllAsync(selector);223 // return eles;224 //}225 //public async Task<bool> elementExist_ByCssSelector(string selector)226 //{227 // ElementHandle ele;228 // if (usingFrame)229 // ele = await frame.QuerySelectorAsync(selector);230 // else231 // ele = await page.QuerySelectorAsync(selector);232 // if (ele != null) return true;233 // else return false;234 //}235 //public async Task ExecuteJS_Script(string jsText)236 //{...

Full Screen

Full Screen

BlazorTest.cs

Source:BlazorTest.cs Github

copy

Full Screen

...247248 await page.GoToAsync("https://github.com/kblok/puppeteer-sharp");249250 var element = await page.QuerySelectorAsync("h1 > strong > a");251 var elements = await page.QuerySelectorAllAsync("a");252253 Assert.NotNull(element);254 Assert.NotEmpty(elements);255256 var missingElement = await page.QuerySelectorAsync("a#missing-link");257 var missingElements = await page.QuerySelectorAllAsync("a.missing-link");258259 Assert.Null(missingElement);260 Assert.Empty(missingElements);261262 var innerHtml = await element.GetPropertyAsync("innerHTML").Result.JsonValueAsync<string>();263 var outerHtml = await element.GetPropertyAsync("outerHTML").Result.JsonValueAsync<string>();264 var url = await element.GetPropertyAsync("href").Result.JsonValueAsync<string>();265266 Assert.Equal("puppeteer-sharp", innerHtml);267 Assert.Equal("<a data-pjax=\"#js-repo-pjax-container\" href=\"/kblok/puppeteer-sharp\">puppeteer-sharp</a>", outerHtml);268 Assert.Equal("https://github.com/kblok/puppeteer-sharp", url);269270 var innerText = await page.QuerySelectorAsync("h1 > strong > a").EvaluateFunctionAsync<string>("node => node.innerText");271 var outerText = await page.QuerySelectorAsync("h1 > strong > a").EvaluateFunctionAsync<string>("node => node.outerText"); ...

Full Screen

Full Screen

Examples.cs

Source:Examples.cs Github

copy

Full Screen

...118 public async Task query()119 {120 await _page.GoToAsync("https://github.com/hardkoded/puppeteer-sharp");121 var element = await _page.QuerySelectorAsync("div#readme");122 var elements = await _page.QuerySelectorAllAsync("div");123 Assert.NotNull(element);124 Assert.NotEmpty(elements);125 var missingElement = await _page.QuerySelectorAsync("div#missing");126 var missingElements = await _page.QuerySelectorAllAsync("div.missing");127 Assert.Null(missingElement);128 Assert.Empty(missingElements);129 var elementInElement = await element.QuerySelectorAsync("h1");130 var elementsInElement = await element.QuerySelectorAllAsync("h1");131 Assert.NotNull(elementInElement);132 Assert.NotEmpty(elementsInElement);133 }134 [Fact]135 public async Task evaluate()136 {137 await _page.GoToAsync("https://github.com/hardkoded/puppeteer-sharp");138 var element = await _page.QuerySelectorAsync("h1 > strong > a");139 var outerHtml = await element.EvaluateFunctionAsync<string>("e => e.outerHTML");140 var innerText = await element.EvaluateFunctionAsync<string>("e => e.innerText");141 var url = await element.EvaluateFunctionAsync<string>("e => e.getAttribute('href')");142 var hasContent = await element.EvaluateFunctionAsync<bool>("(e, value) => e.textContent.includes(value)", "puppeteer-sharp");143 Assert.Equal("<a data-pjax=\"#js-repo-pjax-container\" href=\"/hardkoded/puppeteer-sharp\">puppeteer-sharp</a>", outerHtml);144 Assert.Equal("puppeteer-sharp", innerText);...

Full Screen

Full Screen

Scrape.cs

Source:Scrape.cs Github

copy

Full Screen

...59 await page.GoToAsync(url, timeout: 0);60 string rawTrace = await page.Tracing.StopAsync();61 string content = await page.GetContentAsync();62 //Image63 var imageElements = await page.QuerySelectorAllAsync("img");64 if (imageElements != null)65 {66 imageCount = imageElements.Count();67 imageProperties = await new ImageHelper().GetImageData(imageElements);68 }69 await browser.CloseAsync();70 //Trace71 traces = new TraceHelper().GetTraceData(rawTrace);72 Uri requestUri = new Uri(url);73 string host = requestUri.Host;74 HtmlDocument doc = new HtmlDocument();75 doc.LoadHtml(content);76 var iFrameNodes = doc.DocumentNode.SelectNodes("//iframe");77 var linkNodes = doc.DocumentNode.SelectNodes("//a");...

Full Screen

Full Screen

QuerySelectorAllAsync

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 {9 };10 var browser = await Puppeteer.LaunchAsync(options);11 var page = await browser.NewPageAsync();12 var elements = await page.QuerySelectorAllAsync("input[type=text]");13 Console.WriteLine("Number of elements found: " + elements.Length);14 await browser.CloseAsync();15 }16 }17}18using System;19using System.Threading.Tasks;20using PuppeteerSharp;21{22 {23 static async Task Main(string[] args)24 {25 {26 };27 var browser = await Puppeteer.LaunchAsync(options);28 var page = await browser.NewPageAsync();29 var element = await page.QuerySelectorAsync("input[type=text]");30 Console.WriteLine("Element found: " + element);31 await browser.CloseAsync();32 }33 }34}35using System;36using System.Threading.Tasks;37using PuppeteerSharp;38{39 {40 static async Task Main(string[] args)41 {42 {43 };44 var browser = await Puppeteer.LaunchAsync(options);45 var page = await browser.NewPageAsync();46 var element = await page.QuerySelectorAsync("input[type=text]");47 Console.WriteLine("Element found: " + element);48 await browser.CloseAsync();49 }50 }51}52using System;53using System.Threading.Tasks;54using PuppeteerSharp;55{56 {57 static async Task Main(string[] args)58 {59 {60 };

Full Screen

Full Screen

QuerySelectorAllAsync

Using AI Code Generation

copy

Full Screen

1var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });2var page = await browser.NewPageAsync();3var elements = await page.QuerySelectorAllAsync("a");4foreach (var element in elements)5{6 Console.WriteLine(await element.GetAttributeAsync("href"));7}8await browser.CloseAsync();9var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });10var page = await browser.NewPageAsync();11var element = await page.QuerySelectorAsync("a");12Console.WriteLine(await element.GetAttributeAsync("href"));13await browser.CloseAsync();14var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });15var page = await browser.NewPageAsync();16var elements = await page.QuerySelectorAllAsync("a");17foreach (var element in elements)18{19 Console.WriteLine(await element.GetAttributeAsync("href"));20}21await browser.CloseAsync();22var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });23var page = await browser.NewPageAsync();24var element = await page.QuerySelectorAsync("a");25Console.WriteLine(await element.GetAttributeAsync("href"));26await browser.CloseAsync();27var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });28var page = await browser.NewPageAsync();29var element = await page.QuerySelectorAsync("a");30var elements = await element.QuerySelectorAllAsync("a");31foreach (var el in elements)32{33 Console.WriteLine(await el.GetAttributeAsync("href"));34}35await browser.CloseAsync();36var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });

Full Screen

Full Screen

QuerySelectorAllAsync

Using AI Code Generation

copy

Full Screen

1var browser = await Puppeteer.LaunchAsync(new LaunchOptions2{3});4var page = await browser.NewPageAsync();5var element = await page.QuerySelectorAsync("input");6await element.TypeAsync("Hello World");7await page.Keyboard.PressAsync("Enter");8await page.WaitForNavigationAsync();9var browser = await Puppeteer.LaunchAsync(new LaunchOptions10{11});12var page = await browser.NewPageAsync();13var element = await page.QuerySelectorAsync("input");14await element.TypeAsync("Hello World");15await page.Keyboard.PressAsync("Enter");16await page.WaitForNavigationAsync();17var browser = await Puppeteer.LaunchAsync(new LaunchOptions18{19});20var page = await browser.NewPageAsync();21var element = await page.QuerySelectorAsync("input");22await element.TypeAsync("Hello World");23await page.Keyboard.PressAsync("Enter");24await page.WaitForNavigationAsync();25var browser = await Puppeteer.LaunchAsync(new LaunchOptions26{27});28var page = await browser.NewPageAsync();29var element = await page.QuerySelectorAsync("input");30await element.TypeAsync("Hello World");31await page.Keyboard.PressAsync("Enter");32await page.WaitForNavigationAsync();33var browser = await Puppeteer.LaunchAsync(new LaunchOptions34{35});36var page = await browser.NewPageAsync();37var element = await page.QuerySelectorAsync("input");38await element.TypeAsync("Hello World");39await page.Keyboard.PressAsync("Enter");40await page.WaitForNavigationAsync();

Full Screen

Full Screen

QuerySelectorAllAsync

Using AI Code Generation

copy

Full Screen

1var frame = await page.QuerySelectorAsync("iframe");2var elements = await frame.QuerySelectorAllAsync("a");3foreach (var element in elements)4{5 Console.WriteLine(element.GetAttribute("href"));6}7var elements = await page.QuerySelectorAllAsync("a");8foreach (var element in elements)9{10 Console.WriteLine(element.GetAttribute("href"));11}12var elements = await page.QuerySelectorAsync("a");13foreach (var element in elements)14{15 Console.WriteLine(element.GetAttribute("href"));16}

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