How to use EvaluateFunctionAsync method of PuppeteerSharp.Page class

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

BaseScraper.cs

Source:BaseScraper.cs Github

copy

Full Screen

...92 }93 public virtual async Task<double> GetCurrentScrollHeight(string selector)94 {95 var chSelectorFunc = ScraperConstants.FUNC_SELECT_SIMPLE.Replace("{{SPECIAL}}", ".scrollHeight");96 return await CurrentPage.EvaluateFunctionAsync<double>(chSelectorFunc, selector);97 }98 public virtual async Task<double> GetCurrentScroll(string selector, bool addClientHeight = true)99 {100 var chSelectorFunc = ScraperConstants.FUNC_SELECT_SIMPLE.Replace("{{SPECIAL}}", ".scrollTop");101 var scrollTop = await CurrentPage.EvaluateFunctionAsync<double>(chSelectorFunc, selector);102 if (addClientHeight)103 {104 var clHeightFunc = ScraperConstants.FUNC_SELECT_SIMPLE.Replace("{{SPECIAL}}", ".clientHeight");105 var clientHeight = await CurrentPage.EvaluateFunctionAsync<double>(clHeightFunc, selector);106 scrollTop += clientHeight;107 }108 return scrollTop;109 }110 public virtual async Task ScrollTo(string selector, int toHeight, bool aproximate = true, bool useWindow = false)111 {112 var newHeight = toHeight;113 if (aproximate)114 newHeight -= 100;115 var scrollFuncCall = ".scrollTo(0, " + newHeight + ")";116 var scrollBottom = (useWindow ? ScraperConstants.WINDOW_FUNCTION : ScraperConstants.FUNC_SELECT_SIMPLE).Replace("{{SPECIAL}}", scrollFuncCall);117 await CurrentPage.EvaluateFunctionAsync(scrollBottom, selector);118 }119 public virtual async Task CloseAnnoyingElements()120 {121 var appSettings = SettingsManager.Settings;122 if (appSettings.ANNOYING_ELEMENTS == null || appSettings.ANNOYING_ELEMENTS.Length == 0)123 return;124 await this.CloseAnnoyingElements(appSettings.ANNOYING_ELEMENTS);125 }126 public virtual async Task CloseAnnoyingElements(string[] selectors)127 {128 var stillSearching = true;129 while (stillSearching)130 {131 stillSearching = false;...

Full Screen

Full Screen

Program.cs

Source:Program.cs Github

copy

Full Screen

...62 var jscode = @"() => {63 const selectors = Array.from(document.querySelectorAll(`div.du4w35lb.k4urcfbm.l9j0dhe7.sjgh65i0`)); 64 return selectors.map( t=> {return {content: t.innerHTML}});65 }";66 var results = await page.EvaluateFunctionAsync<Content[]>(jscode);67 List<Data> authorNamesAndText = new List<Data>();68 foreach (var result in results)69 {70 Data data = new Data();71 await page.SetContentAsync(result.content);72 Thread.Sleep(500);73 string content = "", content2 = "";74 var elementHandle = await page.QuerySelectorAsync("span.d2edcug0.hpfvmrgz.qv66sw1b.c1et5uql.lr9zc1uh.a8c37x1j.keod5gw0.nxhoafnm.aigsh9s9.d3f4x2em.fe6kdd0r.mau55g9w.c8b282yb.iv3no6db.jq4qci2q.a3bd9o3v.knj5qynh.m9osqain.hzawbc8m");75 if (elementHandle != null)76 {77 try78 {79 content = await elementHandle.QuerySelectorAsync("span").EvaluateFunctionAsync<string>("node => node.innerText");80 }81 catch (Exception e1)82 {83 Console.WriteLine("error in getting content: " + e1.Message);84 }85 }86 if (content != "")87 {88 Thread.Sleep(500);89 try90 {91 content2 = await page.QuerySelectorAsync("div.kvgmc6g5.cxmmr5t8.oygrvhab.hcukyx3x.c1et5uql.ii04i59q").EvaluateFunctionAsync<string>("node => node.innerText");92 }93 catch (Exception e2)94 {95 Console.WriteLine("error in getting content: " + e2.Message);96 }97 data.author = content;98 data.posttext = content2;99 authorNamesAndText.Add(data);100 }101 }102 //print author and post list103 foreach (Data ap in authorNamesAndText)104 {105 Console.WriteLine("Author: " + ap.author);...

Full Screen

Full Screen

SaveWebPage.xaml.cs

Source:SaveWebPage.xaml.cs Github

copy

Full Screen

...101 PuppeteerSharp.PdfOptions pdfOptions = new PuppeteerSharp.PdfOptions();102 pdfOptions.DisplayHeaderFooter = false; //是否显示页眉页脚103 pdfOptions.FooterTemplate = ""; //页脚文本104105 var width = await page.EvaluateFunctionAsync<int>("function getWidth(){return document.body.scrollWidth}");106 var height = await page.EvaluateFunctionAsync<int>("function getHeight(){return document.body.scrollHeight}");107108 pdfOptions.Width = $"{width}px";109 pdfOptions.Height = $"{height}px";110111 pdfOptions.HeaderTemplate = ""; //页眉文本112 pdfOptions.Landscape = false; //纸张方向 false-垂直 true-水平113 pdfOptions.MarginOptions = new PuppeteerSharp.Media.MarginOptions() { Bottom = "0px", Left = "0px", Right = "0px", Top = "0px" }; //纸张边距,需要设置带单位的值,默认值是None114 pdfOptions.Scale = 1m; //PDF缩放,从0-1115 pdfOptions.PrintBackground = true;116117 var fileName = Environment.CurrentDirectory + $"\\download\\{await page.GetTitleAsync()}.pdf";118119 if (System.IO.File.Exists(fileName))120 { ...

Full Screen

Full Screen

Get-ScraperMobileVikings.cs

Source:Get-ScraperMobileVikings.cs Github

copy

Full Screen

...65 decimal credits;66 try {67 var creditField = await page.WaitForSelectorAsync(68 "body > div:nth-child(1) > div:nth-child(3) > div > div > main > div > section > div > section > section.MvSection.balanceItemSection > div > div > div:nth-child(2) > strong");69 var creditText = await creditField.EvaluateFunctionAsync<string>("e => e.innerText");70 var creditMatch = Regex.Match(creditText, @"^[^\d]*(\d+)[,\.](\d+)$");71 if (creditMatch.Success) {72 creditText = creditMatch.Groups[1].Value + CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator + (creditMatch.Groups[2].Value ?? "0");73 credits = decimal.Parse(creditText, CultureInfo.InvariantCulture.NumberFormat);74 } else {75 throw new Exception($"Credits not found ({creditText})");76 }77 } catch (PuppeteerSharp.WaitTaskTimeoutException) {78 var creditField = await page.WaitForSelectorAsync(79 "body > div:nth-child(1) > div:nth-child(3) > div > div > main > div > section > div > section > section");80 var creditText = await creditField.EvaluateFunctionAsync<string>("e => e.innerText");81 if (creditText.Contains("Geen\nbelwaarde"))82 credits = 0m;83 else84 throw new Exception($"Credits not found (No credits left?)");85 }8687 // Get points88 System.Threading.Thread.Sleep(3000);89 decimal? points = null;90 if (!DontIncludePoints)91 {92 await page.GoToAsync("https://mobilevikings.be/en/my-viking/viking-points");93 Match pointMatch = null;94 string pointText = "";95 for (int i = 0; i < 10 && (pointMatch == null || !pointMatch.Success); i++)96 {97 System.Threading.Thread.Sleep(1000);98 var pointField = await page.WaitForSelectorAsync(99 "body > div:nth-child(1) > div:nth-child(3) > div > div > main > div > section.vikingPointsView__header.vikingPointsViewHeader > div.vikingPointsViewHeader__details.vikingPointsViewHeaderItem.available > div");100 pointText = await pointField.EvaluateFunctionAsync<string>("e => e.innerText");101 pointMatch = Regex.Match(pointText, @"^[^\d]*(\d+)[,\.](\d+)$");102 }103 if (pointMatch.Success) {104 pointText = pointMatch.Groups[1].Value + CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator + (pointMatch.Groups[2].Value ?? "0");105 points = decimal.Parse(pointText, CultureInfo.InvariantCulture.NumberFormat);106 } else {107 throw new Exception($"Points not found ({pointText})");108 }109 }110111 // Bundle112 return new MobileVikings { 113 Credits = credits,114 Points = points ...

Full Screen

Full Screen

AvitoPostParser.cs

Source:AvitoPostParser.cs Github

copy

Full Screen

...43 };44 }45 private async Task<string> GetAuthorName(PuppeteerSharp.Page page)46 {47 var sellerInfoName = await page.WaitForSelectorAsync(".seller-info-name.js-seller-info-name a").EvaluateFunctionAsync<string>("element => element.innerHTML");48 sellerInfoName = sellerInfoName.Trim();49 var sellerInfoValueElement = await page.QuerySelectorAsync("div.seller-info-label + div.seller-info-value");50 if (sellerInfoValueElement != null)51 {52 var sellerInfoValue = (await sellerInfoValueElement.EvaluateFunctionAsync<string>("element => element.innerHTML")).Trim();53 sellerInfoName += ": " + sellerInfoValue;54 }55 return sellerInfoName;56 }57 private async Task<string> GetPhoneNumber(PuppeteerSharp.Page page)58 {59 string phoneImage = await page.WaitForSelectorAsync("div[data-marker='phone-popup/content'] img[data-marker='phone-popup/phone-image']").EvaluateFunctionAsync<string>("element => element.src");60 string imageStr = phoneImage.Substring(phoneImage.IndexOf(",") + 1).Trim();61 byte[] imageByte = System.Convert.FromBase64String(imageStr);62 using (var engine = new TesseractEngine("./tessdata", "eng", EngineMode.Default))63 {64 using (var memoryStream = new MemoryStream(imageByte))65 {66 var file = Pix.LoadFromMemory(memoryStream.ToArray());67 var page1 = engine.Process(file);68 return page1.GetText().Trim();69 }70 }71 }72 }73}...

Full Screen

Full Screen

test vueJS.csx

Source:test vueJS.csx Github

copy

Full Screen

...50async Task waitForProgramEnd(){51 /*52 This stuff keeps the browser open until our program is done.53 */54 await page.EvaluateFunctionAsync(@"55 ()=> {56 window.programDone = false;57 }58 ");59 await page.WaitForExpressionAsync("window.programDone === true", new WaitForFunctionOptions{60 Timeout = 0 // disable timeout61 });62 Console.WriteLine("Program finished triggered");63 // program is done so close everything out64 await page.CloseAsync();65 await browser.CloseAsync();66}67await waitForProgramEnd();...

Full Screen

Full Screen

PuppeteerHelper.cs

Source:PuppeteerHelper.cs Github

copy

Full Screen

...8 public static class PuppeteerHelper9 {10 public static async Task<string> GetTextboxValue(Page page, string selector)11 {12 JToken value = await page.EvaluateFunctionAsync(@"(selector) => {13 return document.querySelector(selector).value;14 }", selector);15 return value.Value<string>();16 }17 public static async Task<JToken> GetTableData(Page page, string dataSelector, List<ScrapeItemSetting> mappings)18 {19 var tData = await page.EvaluateFunctionAsync(@"(dataSelector, tableMapping) => {20 const data = Array.from(document.querySelectorAll(dataSelector));21 var items = [];22 data.forEach((item, index) => {23 var obj = {};24 tableMapping.forEach((i, idx) => {25 setObject(obj, i, item);26 });27 items.push(obj);28 });29 return items;30 }", dataSelector, mappings);31 return tData;32 }33 public static async Task<JToken> GetElements(Page page, List<ScrapeItemSetting> mappings)34 {35 var tData = await page.EvaluateFunctionAsync(@"(mappings) => {36 var items = [];37 mappings.forEach((i, idx) => {38 var obj = {};39 var element = $(document);40 setObject(obj, i, element);41 items.push(obj);42 });43 return items;44 }", mappings);45 return tData;46 }47 }48}...

Full Screen

Full Screen

CapturingService.cs

Source:CapturingService.cs Github

copy

Full Screen

1using PuppeteerSharp;2namespace HeadfulBrowserAudioVideoCapturingService;3public class CapturingService4{5 public async Task StartCapturing(Page extensionPage) => await extensionPage.EvaluateFunctionAsync("START_RECORDING", new StartRecordingSettings());6 public async Task StopCapturing(Page extensionPage) => await extensionPage.EvaluateFunctionAsync("STOP_RECORDING");7}...

Full Screen

Full Screen

EvaluateFunctionAsync

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

Full Screen

Full Screen

EvaluateFunctionAsync

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 });11 var page = await browser.NewPageAsync();12 var result = await page.EvaluateFunctionAsync("() => 1 + 2");13 Console.WriteLine(result);14 await browser.CloseAsync();15 }16 }17}18public Task<JsonElement> EvaluateExpressionAsync(string expression, object[] args = null)19using System;20using System.Threading.Tasks;21using PuppeteerSharp;22{23 {24 static async Task Main(string[] args)25 {26 var browser = await Puppeteer.LaunchAsync(new LaunchOptions27 {28 });29 var page = await browser.NewPageAsync();30 var result = await page.EvaluateExpressionAsync("1 + 2");31 Console.WriteLine(result);32 await browser.CloseAsync();33 }34 }35}36public Task<JSHandle> EvaluateFunctionHandleAsync(string function, object[] args = null)

Full Screen

Full Screen

EvaluateFunctionAsync

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 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"10 };11 using (var browser = await Puppeteer.LaunchAsync(options))12 using (var page = await browser.NewPageAsync())13 {14 var result = await page.EvaluateFunctionAsync<string>("() => { return 'hello world'; }");15 Console.WriteLine(result);16 }17 }18 }19}

Full Screen

Full Screen

EvaluateFunctionAsync

Using AI Code Generation

copy

Full Screen

1{2 {3 static void Main(string[] args)4 {5 var task = MainAsync(args);6 task.Wait();7 }8 static async Task MainAsync(string[] args)9 {10 var browser = await Puppeteer.LaunchAsync(new LaunchOptions11 {12 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",13 Args = new string[] { "--no-sandbox" }14 });15 var page = await browser.NewPageAsync();16 var result = await page.EvaluateFunctionAsync("() => { return 1 + 2; }");17 Console.WriteLine(result);18 Console.ReadKey();19 }20 }21}

Full Screen

Full Screen

EvaluateFunctionAsync

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 });11 var page = await browser.NewPageAsync();12 var h1Value = await page.EvaluateFunctionAsync<string>("() => document.querySelector('h1').innerText");13 Console.WriteLine("h1 value is: " + h1Value);14 Console.ReadLine();15 await browser.CloseAsync();16 }17 }18}

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