Best Puppeteer-sharp code snippet using PuppeteerSharp.ConnectOptions
WorkerActivities.cs
Source:WorkerActivities.cs
...21 [ActivityTrigger] DurableActivityContext ctx,22 TraceWriter log)23 {24 var credentials = ctx.GetInput<string>();25 var browser = await Puppeteer.ConnectAsync(new ConnectOptions { BrowserWSEndpoint = Constants.BrowserWSEndpoint });26 var page = await browser.NewPageAsync();27 var login = new UIAction.Login();28 CookieParam[] cookies = null;29 cookies = await login.RunAsync(page, log);30 // page is closed implicitly31 browser.Disconnect();32 if (cookies != null)33 {34 return CookieConverter.EncodeCookie(cookies);35 }36 throw new Exception("Failed to authenticate.");37 }38 // A) Accept search query and cookies return [totalpages]39 [FunctionName("QueryGuru")]40 public static async Task<int> QueryGuru(41 [ActivityTrigger] DurableActivityContext ctx,42 TraceWriter log)43 {44 var arguments = ctx.GetInput<Tuple<string, string>>();45 var searchargs = arguments.Item1.Split(':');46 if (searchargs.Length != 2)47 {48 throw new ArgumentException("Activity.QueryGuru: Expected search query to be in format <query>:<type>");49 }50 var query = searchargs[0];51 var type = searchargs[1];52 var cookies = CookieConverter.DecodeCookie(arguments.Item2);53 var browser = await Puppeteer.ConnectAsync(new ConnectOptions { BrowserWSEndpoint = Constants.BrowserWSEndpoint });54 var page = await browser.NewPageAsync();55 await page.SetCookieAsync(cookies);56 var search = new UIAction.NavigateSearch(query, type);57 var pages = await search.RunAsync(page);58 browser.Disconnect();59 return pages;60 }61 // O) Accept search query and cookies and page and configsection then return result62 [FunctionName("RetrievePageContent")]63 public static async Task<WorkerResult> RetrievePageContent(64 [ActivityTrigger] DurableActivityContext ctx,65 TraceWriter log)66 {67 var arguments = ctx.GetInput<Tuple<string, string, int, string>>();68 var searchargs = arguments.Item1.Split(':');69 if (searchargs.Length != 2)70 {71 throw new ArgumentException("Activity.QueryGuru: Expected search query to be in format <query>:<type>");72 }73 var query = searchargs[0];74 var type = searchargs[1];75 var cookies = CookieConverter.DecodeCookie(arguments.Item2);76 var pagenumber = arguments.Item3;77 var config = JsonConvert.DeserializeObject<ConfigSection>(arguments.Item4);78 var browser = await Puppeteer.ConnectAsync(new ConnectOptions { BrowserWSEndpoint = Constants.BrowserWSEndpoint });79 var page = await browser.NewPageAsync();80 await page.SetCookieAsync(cookies);81 var search = new UIAction.NavigateSearch(query, type, true);82 await search.RunAsync(page);83 var collect = new UIAction.NavigateCollect(pagenumber, ctx.InstanceId, ctx.InstanceId, config);84 var result = await collect.RunAsync(page);85 // page is closed implicitly86 browser.Disconnect();87 var customresult = new WorkerResult { html = result, page = pagenumber };88 return customresult;89 }90 // A) Accept number of pages and return a range from 1 to number of pages91 [FunctionName("CreateWorkload")]92 public static async Task<List<int>> CreateWorkload(93 [ActivityTrigger] DurableActivityContext ctx,94 TraceWriter log)95 {96 var totalpages = ctx.GetInput<int>();97 var workload = Enumerable.Range(1, totalpages).ToList();98 return await Task.FromResult(workload);99 }100 // A) Accept number of pages and return a range from 1 to number of pages101 [FunctionName("RaiseFinishedEvent")]102 public static async Task RaiseFinishedEvent(103 [ActivityTrigger] DurableActivityContext ctx,104 [OrchestrationClient] DurableOrchestrationClient client,105 TraceWriter log)106 {107 var args = ctx.GetInput<WorkerWorkResult>();108 var instanceid = args.instanceid;109 var reason = args.result;110 await client.RaiseEventAsync(instanceid, "Finished", reason);111 }112 [FunctionName("RetrieveScrapingConfig")]113 public static async Task<ConfigSection> RetrieveScrapingConfig(114 [ActivityTrigger] DurableActivityContext ctx,115 [Blob("config/propertyrecord.json", Connection = "StorageAccount")] TextReader file,116 TraceWriter log)117 {118 var configjson = await file.ReadToEndAsync();119 var config = OpenScraping.Config.StructuredDataConfig.ParseJsonString(configjson);120 return await Task.FromResult(config);121 }122 // [FunctionName("A_InitBrowser")]123 // public static async Task<string> InitBrowser(124 // [ActivityTrigger] DurableActivityContext ctx,125 // TraceWriter log)126 // {127 // var connectionstring = ctx.GetInput<string>();128 // var browser = await Puppeteer.ConnectAsync(new ConnectOptions { BrowserWSEndpoint = connectionstring });129 // var json = JsonConvert.SerializeObject(browser, Formatting.None, new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.All, TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Full });130 // return json;131 // }132 // [FunctionName("A_InitBrowserPage")]133 // public static async Task<Page> InitBrowserPage(134 // [ActivityTrigger] DurableActivityContext ctx,135 // TraceWriter log)136 // {137 // var browser = ctx.GetInput<Browser>();138 // var page = await browser.NewPageAsync();139 // return page;140 // }141 // [FunctionName("A_ScrapeSingle")]142 // public static async Task<Model.WorkerResult> ScrapeSingle(...
PDFService.cs
Source:PDFService.cs
...49 private async Task GeneratePdfAsync(string url, string outputPath)50 {51 try52 {53 var connectOptions = new ConnectOptions54 {55 BrowserWSEndpoint = await GetWebSocketDebuggerUrl()56 };57 var browser = await Puppeteer.ConnectAsync(connectOptions);58 using (var page = await browser.NewPageAsync())59 {60 await page.GoToAsync(url, new NavigationOptions61 {62 Timeout = 0,63 WaitUntil = new[] { WaitUntilNavigation.Networkidle2 }64 });65 await page.PdfAsync(outputPath, new PdfOptions66 {67 Width = _pdfServiceConfig.PaperWidth,...
ApiFactory.cs
Source:ApiFactory.cs
...81 sourceWriter.Namespace("Weikio.ApiFramework.Plugins.Browser");82 sourceWriter.StartClass($"RemoteBrowser : WebBrowser");83 sourceWriter.WriteLine($"private readonly string _browserWSEndpoint = \"{configuration?.BrowserWSEndpoint}\";");84 sourceWriter.Write(85 "protected override async Task<PuppeteerSharp.Browser> GetBrowser() { var connectOptions = new ConnectOptions() { BrowserWSEndpoint = _browserWSEndpoint };var result = await Puppeteer.ConnectAsync(connectOptions); return result; }");86 sourceWriter.FinishBlock(); // Finish the class87 sourceWriter.FinishBlock(); // Finish the namespace88 code = sourceWriter.ToString();89 }90 var generator = new CodeToAssemblyGenerator();91 generator.ReferenceAssemblyContainingType<WebBrowser>();92 generator.ReferenceAssemblyContainingType<PuppeteerSharp.Browser>();93 var assembly = generator.GenerateAssembly(code);94 var result = assembly.GetExportedTypes()95 .ToList();96 return result;97 }98 public static string GetBrowserPath()99 {...
Program.cs
Source:Program.cs
...31 var LaunchOptions = new LaunchOptions32 {33 Headless = false34 };35 var ConnectOptions = new ConnectOptions()36 {37 BrowserWSEndpoint = wsChromeEndpointurl38 };39 //var url = "https://www.google.com/";40 //await Puppeteer.LaunchAsync(LaunchOptions);41 //using (var browser = await Puppeteer.LaunchAsync(LaunchOptions))42 using (var browser = await PuppeteerSharp.Puppeteer.ConnectAsync(ConnectOptions))43 using (var page = await browser.NewPageAsync())44 {45 Uber.page = page;46 var user = Credentials.Uber.user;47 var password = Credentials.Uber.password;48 await Uber.Login(user, password);49 }50 }51 public static async Task TestBanorte ()52 {53 var token = Console.ReadLine();54 var user = Credentials.Banorte.user;55 var password = Credentials.Banorte.password;56 await Banorte.Login(user, password, token);...
ChromeHelper.cs
Source:ChromeHelper.cs
...18 _logger = logger;19 _chromeSettings = chromeSettings;20 _configuration = configuration;21 }22 public async Task<ConnectOptions> GetConnectOptionsAsync()23 {24 var options = new ConnectOptions25 {26 BrowserWSEndpoint = await GetWSEndpoint()27 };28 return options;29 }30 private async Task<string> GetWSEndpoint()31 {32 try33 {34 var uri = new Uri($"http://{_chromeSettings.Host}:{_chromeSettings.Port}/json/version");35 var request = new HttpRequestMessage(HttpMethod.Get, uri);36 request.Headers.Add("Host", $"localhost:{_chromeSettings.Port}");37 38 _logger.LogTrace($"Getting chrome ws endpoint from {uri}");...
BrowserProvider.cs
Source:BrowserProvider.cs
...22 if (!string.IsNullOrEmpty(Options.BrowserWsEndpoint))23 {24 logger.LogInformation("Connect to ws endpoint");25 return await PuppeteerSharp.Puppeteer.ConnectAsync(26 new ConnectOptions27 {28 BrowserWSEndpoint = Options.BrowserWsEndpoint,29 IgnoreHTTPSErrors = Options.IgnoreHTTPSErrors,30 DefaultViewport = Options.ViewPortOptions31 },32 loggerFactory);33 }34 if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("PUPPETEER_EXECUTABLE_PATH")))35 {36 logger.LogDebug("Download browser");37 using var browserFetcher = new BrowserFetcher(Options.Product);38 if (!string.IsNullOrEmpty(Options.Revision))39 {40 await browserFetcher.DownloadAsync(Options.Revision);...
Browser.cs
Source:Browser.cs
...20 // {21 // Headless = true,22 // Args = new[] { "--disable-gpu", "--disable-dev-shm-usage", "--no-sandbox", "--disable-setuid-sandbox" }23 // });24 _puppeteerBrowser = await Puppeteer.ConnectAsync(new ConnectOptions { BrowserWSEndpoint = "ws://chrome:3000" });25 }26}...
ImageService.cs
Source:ImageService.cs
...11 _config = config;12 }13 public async Task GenerateImageAsync()14 {15 var browser = await Puppeteer.ConnectAsync(new ConnectOptions16 {17 BrowserWSEndpoint = _config.GetSection(BrowserWSKey).Value18 });19 var page = await browser.NewPageAsync();20 await page.GoToAsync("https://www.google.com");21 await page.ScreenshotAsync("screenshot.png");22 }23 }24}
ConnectOptions
Using AI Code Generation
1using PuppeteerSharp;2using System;3using System.Threading.Tasks;4{5 {6 static async Task Main(string[] args)7 {8 {
ConnectOptions
Using AI Code Generation
1using PuppeteerSharp;2using System;3using System.Threading.Tasks;4{5 {6 static async Task Main(string[] args)7 {8 {9 };10 var browser = await Puppeteer.ConnectAsync(options);11 var page = await browser.NewPageAsync();12 await page.ScreenshotAsync("google.png");13 await browser.CloseAsync();14 }15 }16}
ConnectOptions
Using AI Code Generation
1using PuppeteerSharp;2using System;3using System.Threading.Tasks;4{5 {6 static async Task Main(string[] args)7 {8 {
ConnectOptions
Using AI Code Generation
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.ConnectAsync(options);11 var page = await browser.NewPageAsync();12 await page.ScreenshotAsync("example.png");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 var browserFetcher = new BrowserFetcher();25 await browserFetcher.DownloadAsync(BrowserFetcher.DefaultRevision);26 var browser = await Puppeteer.LaunchAsync(new LaunchOptions27 {28 ExecutablePath = browserFetcher.GetExecutablePath(BrowserFetcher.DefaultRevision),29 });30 var page = await browser.NewPageAsync();31 await page.ScreenshotAsync("example.png");32 await browser.CloseAsync();33 }34 }35}36using System;37using System.Threading.Tasks;38using PuppeteerSharp;39{40 {41 static async Task Main(string[] args)42 {43 var browser = await Puppeteer.LaunchAsync();44 var page = await browser.NewPageAsync();45 await page.ScreenshotAsync("example.png");46 await browser.CloseAsync();47 }48 }49}50using System;51using System.Threading.Tasks;52using PuppeteerSharp;53{54 {55 static async Task Main(string[] args)56 {
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!