How to use EvaluateExpressionAsync method of PuppeteerSharp.Page class

Best Puppeteer-sharp code snippet using PuppeteerSharp.Page.EvaluateExpressionAsync

Methods.cs

Source:Methods.cs Github

copy

Full Screen

...20 data.Logger.LogHeader();21 var elemScript = GetElementScript(findBy, identifier, index);22 var frame = GetFrame(data);23 var script = elemScript + $".setAttribute('{attributeName}', '{value}');";24 await frame.EvaluateExpressionAsync(script);25 data.Logger.Log($"Set value {value} of attribute {attributeName} by executing {script}", LogColors.DarkSalmon);26 }27 [Block("Types text in an input field", name = "Type")]28 public static async Task PuppeteerTypeElement(BotData data, FindElementBy findBy, string identifier, int index,29 string text, int timeBetweenKeystrokes = 0)30 {31 data.Logger.LogHeader();32 var frame = GetFrame(data);33 var elem = await GetElement(frame, 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 GetElement(frame, 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 GetElement(frame, 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 GetElement(frame, findBy, identifier, index);78 await elem.SelectAsync(value);79 data.Logger.Log($"Selected value {value}", LogColors.DarkSalmon);80 }81 [Block("Selects a value by index in a select element", name = "Select by Index")]82 public static async Task PuppeteerSelectByIndex(BotData data, FindElementBy findBy, string identifier, int index, int selectionIndex)83 {84 data.Logger.LogHeader();85 var frame = GetFrame(data);86 var elemScript = GetElementScript(findBy, identifier, index);87 var script = elemScript + $".getElementsByTagName('option')[{selectionIndex}].value;";88 var value = (await frame.EvaluateExpressionAsync(script)).ToString();89 var elem = await GetElement(frame, findBy, identifier, index);90 await elem.SelectAsync(value);91 data.Logger.Log($"Selected value {value}", LogColors.DarkSalmon);92 }93 [Block("Selects a value by text in a select element", name = "Select by Text")]94 public static async Task PuppeteerSelectByText(BotData data, FindElementBy findBy, string identifier, int index, string text)95 {96 data.Logger.LogHeader();97 var frame = GetFrame(data);98 var elemScript = GetElementScript(findBy, identifier, index);99 var script = $"el={elemScript};for(let i=0;i<el.options.length;i++){{if(el.options[i].text=='{text}'){{el.selectedIndex = i;break;}}}}";100 await frame.EvaluateExpressionAsync(script);101 data.Logger.Log($"Selected text {text}", LogColors.DarkSalmon);102 }103 [Block("Gets the value of an attribute of an element", name = "Get Attribute Value")]104 public static async Task<string> PuppeteerGetAttributeValue(BotData data, FindElementBy findBy, string identifier, int index,105 string attributeName = "innerText")106 {107 data.Logger.LogHeader();108 var elemScript = GetElementScript(findBy, identifier, index);109 var frame = GetFrame(data);110 var script = $"{elemScript}.{attributeName};";111 var value = await frame.EvaluateExpressionAsync<string>(script);112 data.Logger.Log($"Got value {value} of attribute {attributeName} by executing {script}", LogColors.DarkSalmon);113 return value;114 }115 [Block("Gets the values of an attribute of multiple elements", name = "Get Attribute Value All")]116 public static async Task<List<string>> PuppeteerGetAttributeValueAll(BotData data, FindElementBy findBy, string identifier,117 string attributeName = "innerText")118 {119 data.Logger.LogHeader();120 var elemScript = GetElementsScript(findBy, identifier);121 var frame = GetFrame(data);122 var script = $"Array.prototype.slice.call({elemScript}).map((item) => item.{attributeName})";123 var values = await frame.EvaluateExpressionAsync<string[]>(script);124 data.Logger.Log($"Got {values.Length} values for attribute {attributeName} by executing {script}", LogColors.DarkSalmon);125 return values.ToList();126 }127 [Block("Checks if an element is currently being displayed on the page", name = "Is Displayed")]128 public static async Task<bool> PuppeteerIsDisplayed(BotData data, FindElementBy findBy, string identifier, int index)129 {130 data.Logger.LogHeader();131 var elemScript = GetElementScript(findBy, identifier, index);132 var frame = GetFrame(data);133 var script = $"window.getComputedStyle({elemScript}).display !== 'none';";134 var displayed = await frame.EvaluateExpressionAsync<bool>(script);135 data.Logger.Log($"Found out the element is{(displayed ? "" : " not")} displayed by executing {script}", LogColors.DarkSalmon);136 return displayed;137 }138 [Block("Checks if an element exists on the page", name = "Exists")]139 public static async Task<bool> PuppeteerExists(BotData data, FindElementBy findBy, string identifier, int index)140 {141 data.Logger.LogHeader();142 var elemScript = GetElementScript(findBy, identifier, index);143 var frame = GetFrame(data);144 var script = $"window.getComputedStyle({elemScript}).display !== 'none';";145 try146 {147 var displayed = await frame.EvaluateExpressionAsync<bool>(script);148 data.Logger.Log("The element exists", LogColors.DarkSalmon);149 return true;150 }151 catch152 {153 data.Logger.Log("The element does not exist", LogColors.DarkSalmon);154 return false;155 }156 }157 [Block("Uploads one or more files to the selected element", name = "Upload Files")]158 public static async Task PuppeteerUploadFiles(BotData data, FindElementBy findBy, string identifier, int index, List<string> filePaths)159 {160 data.Logger.LogHeader();161 var frame = GetFrame(data);...

Full Screen

Full Screen

PuppeteerMethods.cs

Source:PuppeteerMethods.cs Github

copy

Full Screen

...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

Program.cs

Source:Program.cs Github

copy

Full Screen

...23 });24 var page = await browser.NewPageAsync();25 await page.GoToAsync("https://www.swedishbulls.com/SignalPage.aspx?lang=en&Ticker=8TRA.ST");2627 //await page.EvaluateExpressionAsync("document.getElementById('MainContent_uEmail').value = " + "'gurka@gmail.com'");28 //await page.EvaluateExpressionAsync("document.getElementById('MainContent_uPassword').value = " + "'passwörd'");29 //await page.EvaluateExpressionAsync("document.getElementById('MainContent_btnSubmit').click()");30 //await page.SetViewportAsync(new ViewPortOptions31 //{32 // Width = 1024,33 // Height = 78034 //});3536 37 var element = await page.QuerySelectorAsync("#MainContent_ASPxRoundPanel2_WebChartControl1_IMG");38 //var element = await page.EvaluateExpressionAsync<ElementHandle>("document.getElementById('MainContent_ASPxRoundPanel2_WebChartControl1_IMG')");39 await element.ScreenshotAsync("gurka.png");4041 //await page.ScreenshotAsync("test.png", new ScreenshotOptions42 //{43 // Clip = new Clip()44 // {45 // X = 10,46 // Y = 10,47 // Height = 100,48 // Width = 10049 // }50 //});515253 var res= await page.EvaluateExpressionAsync<string>("document.getElementById('MainContent_signalpagedailycommentarytext').textContent");5455 element = await page.QuerySelectorAsync("#MainContent_signalpagedailycommentarytext");56 var apaaoa = (await element.GetPropertyAsync("textContent")).JsonValueAsync() ;57 //var res = await element.EvaluateFunctionAsync<string>("textContent");5859 await browser.CloseAsync();606162 //var client = new SwedishBullsClient();63 ////var s = await client.GetSnapshot("8TRA.ST");64 ////Console.WriteLine(s.SignalUpdate);65 ////Console.WriteLine(s.MarketOutlook);6667 //await client.Login("test@gmail.com", "test"); ...

Full Screen

Full Screen

ShakespeareTranslationService.cs

Source:ShakespeareTranslationService.cs Github

copy

Full Screen

...37 using (var page = await _browser.NewPageAsync())38 {39 await page.GoToAsync("https://lingojam.com/EnglishtoShakespearean");40 // Clear text41 await page.EvaluateExpressionAsync("$('#english-text').val('')");42 await page.EvaluateExpressionAsync("$('#ghetto-text').val('')");43 // Set text44 //await page.EvaluateExpressionAsync($"$('#english-text').val('{text}')");45 await page.FocusAsync("#english-text");46 await page.Keyboard.TypeAsync(text, new TypeOptions() { Delay = 10 }); ;47 // Read translated text until we have same read twice48 // This is used with the purpose of waiting the correct text to be displayed49 // Could be achievied checking for the gif load animation status but we go with this solution50 // for semplicity51 string[] readAttempt = { string.Empty, string.Empty };52 int index = 0;53 var translatedTextSelector = @"document.querySelector('#ghetto-text').value;";54 while (true)55 {56 // Wait 1 sec57 await Task.Delay(1000);58 readAttempt[index % 2] = await page.EvaluateExpressionAsync<string>(translatedTextSelector);59 index++;60 if (index < 2)61 continue;62 if (string.Compare(readAttempt[0], readAttempt[1]) == 0)63 {64 translatedText = readAttempt[0];65 break;66 }67 }68 }69 }70 return translatedText;71 }72 }...

Full Screen

Full Screen

InstagramService.cs

Source:InstagramService.cs Github

copy

Full Screen

...35 description: child.alt, 36 src: child.src37 }38 })";39 var images = await page.EvaluateExpressionAsync<Image[]>(jsSelectAllAnchors);40 result = images;41 await page.CloseAsync();42 }43 }44 catch 45 {46 }47 return result;48 }49 }50}...

Full Screen

Full Screen

BrowserTests.cs

Source:BrowserTests.cs Github

copy

Full Screen

...30 await Browser?.CloseAsync();31 }32 private async Task PrintPerf(Page page)33 {34 var perf = await page.EvaluateExpressionAsync<long>("window.performance.timing.domContentLoadedEventEnd - window.performance.timing.navigationStart");35 Console.WriteLine($"Load Time: {perf}ms");36 }37 [Fact]38 public async Task CheckRoot()39 {40 bool hasError = false;41 var page = await Browser.NewPageAsync();42 page.Console += Page_Console;43 void Page_Console(object sender, ConsoleEventArgs e)44 {45 if (e.Message.Type == ConsoleType.Error)46 hasError = true;47 }48 await page.GoToAsync(BaseAddress);...

Full Screen

Full Screen

EmulateMediaTests.cs

Source:EmulateMediaTests.cs Github

copy

Full Screen

...12 }13 [Fact]14 public async Task ShouldWork()15 {16 Assert.True(await Page.EvaluateExpressionAsync<bool>("window.matchMedia('screen').matches"));17 Assert.False(await Page.EvaluateExpressionAsync<bool>("window.matchMedia('print').matches"));18 await Page.EmulateMediaAsync(MediaType.Print);19 Assert.False(await Page.EvaluateExpressionAsync<bool>("window.matchMedia('screen').matches"));20 Assert.True(await Page.EvaluateExpressionAsync<bool>("window.matchMedia('print').matches"));21 await Page.EmulateMediaAsync(MediaType.None);22 Assert.True(await Page.EvaluateExpressionAsync<bool>("window.matchMedia('screen').matches"));23 Assert.False(await Page.EvaluateExpressionAsync<bool>("window.matchMedia('print').matches"));24 }25 }26}...

Full Screen

Full Screen

ConvertController.cs

Source:ConvertController.cs Github

copy

Full Screen

...17 Headless = true,18 });19 var page = await browser.NewPageAsync();20 await page.GoToAsync(url);21 await page.EvaluateExpressionAsync(@"22 for(var ele of document.querySelectorAll('.pagination')){23 ele.classList.remove('pagination');24 }");25 return File(await page.PdfStreamAsync(new PdfOptions() {26 Format = PaperFormat.A427 }), "application/pdf");28 }29 }30}

Full Screen

Full Screen

EvaluateExpressionAsync

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 var options = new LaunchOptions { Headless = false };9 using (var browser = await Puppeteer.LaunchAsync(options))10 using (var page = await browser.NewPageAsync())11 {12 string title = await page.EvaluateExpressionAsync<string>("document.title");13 Console.WriteLine(title);14 }15 }16 }17}18using System;19using System.Threading.Tasks;20using PuppeteerSharp;21{22 {23 static async Task Main(string[] args)24 {25 var options = new LaunchOptions { Headless = false };26 using (var browser = await Puppeteer.LaunchAsync(options))27 using (var page = await browser.NewPageAsync())28 {29 string title = await page.MainFrame.EvaluateExpressionAsync<string>("document.title");30 Console.WriteLine(title);31 }32 }33 }34}35using System;36using System.Threading.Tasks;37using PuppeteerSharp;38{39 {40 static async Task Main(string[] args)41 {42 var options = new LaunchOptions { Headless = false };43 using (var browser = await Puppeteer.LaunchAsync(options))44 using (var page = await browser.NewPageAsync())45 {46 var element = await page.QuerySelectorAsync("input[name='q']");47 string value = await element.EvaluateExpressionAsync<string>("element => element.value");48 Console.WriteLine(value);49 }50 }51 }52}53using System;54using System.Threading.Tasks;55using PuppeteerSharp;56{57 {58 static async Task Main(string[] args)59 {60 var options = new LaunchOptions { Headless = false };61 using (var browser = await Puppeteer.LaunchAsync(options

Full Screen

Full Screen

EvaluateExpressionAsync

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 var browser = await Puppeteer.LaunchAsync(new LaunchOptions9 {10 Args = new string[] { "--start-maximized" }11 });12 var page = await browser.NewPageAsync();13 await page.TypeAsync("input[title='Search']", "hello");14 var result = await page.EvaluateExpressionAsync<string>("document.querySelector('input[title=\"Search\"]').value");15 Console.WriteLine(result);16 await browser.CloseAsync();17 }18 }19}

Full Screen

Full Screen

EvaluateExpressionAsync

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 MainAsync(args).GetAwaiter().GetResult();9 }10 static async Task MainAsync(string[] args)11 {12 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);13 var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false });14 var page = await browser.NewPageAsync();15 var result = await page.EvaluateExpressionAsync<int>("10 + 10");16 Console.WriteLine(result);17 await browser.CloseAsync();18 }19 }20}

Full Screen

Full Screen

EvaluateExpressionAsync

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 LaunchOptions10 {11 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",12 });13 var page = await browser.NewPageAsync();14 var frame = page.MainFrame;15 var result = await frame.EvaluateExpressionAsync<int>("1+2");16 Console.WriteLine(result);17 await page.CloseAsync();18 await browser.CloseAsync();19 }20 }21}22using System;23using System.Threading.Tasks;24using PuppeteerSharp;25{26 {27 static async Task Main(string[] args)28 {29 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);30 var browser = await Puppeteer.LaunchAsync(new LaunchOptions31 {32 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",33 });34 var page = await browser.NewPageAsync();35 var frame = page.MainFrame;36 var result = await frame.EvaluateFunctionAsync<int>("(a,b)=>a+b", 1, 2);37 Console.WriteLine(result);38 await page.CloseAsync();39 await browser.CloseAsync();40 }41 }42}43using System;44using System.Threading.Tasks;45using PuppeteerSharp;46{47 {48 static async Task Main(string[] args)49 {50 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);51 var browser = await Puppeteer.LaunchAsync(new LaunchOptions52 {

Full Screen

Full Screen

EvaluateExpressionAsync

Using AI Code Generation

copy

Full Screen

1var page = await browser.NewPageAsync();2var result = await page.EvaluateExpressionAsync<object>("1+1");3var page = await browser.NewPageAsync();4var result = await page.EvaluateFunctionAsync<object>("() => 1+1");5var page = await browser.NewPageAsync();6var result = await page.EvaluateExpressionHandleAsync<object>("1+1");7var page = await browser.NewPageAsync();8var result = await page.EvaluateFunctionHandleAsync<object>("() => 1+1");

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.

Run Puppeteer-sharp automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in Page

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful