How to use ConnectAsync method of PuppeteerSharp.Puppeteer class

Best Puppeteer-sharp code snippet using PuppeteerSharp.Puppeteer.ConnectAsync

WorkerActivities.cs

Source:WorkerActivities.cs Github

copy

Full Screen

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

Full Screen

Full Screen

ApiFactory.cs

Source:ApiFactory.cs Github

copy

Full Screen

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

Full Screen

Full Screen

ManageHeadlessBrowser.cs

Source:ManageHeadlessBrowser.cs Github

copy

Full Screen

...43 var policy = Policy44 .Handle<Exception>()45 .WaitAndRetryAsync(delay, onRetry: (response, delay, retryCount, context) =>46 {47 _logger.LogInformation($"******* retry ConnectAsync #{retryCount}{Environment.NewLine}");48 });49 await policy.ExecuteAsync(async () =>50 {51 _logger.LogInformation($"******* trying to connect to headless browser.{Environment.NewLine}");52 _browser = await PuppeteerSharp.Puppeteer.ConnectAsync(options);53 });54 }55 /// <summary>56 /// lets create/get browser pages based on index57 /// </summary>58 /// <param name="index">concurrency index</param>59 /// <returns>Puppeteer Page object</returns>60 public async Task<T> GetPage<T>(int index) where T : class61 {62 if (_browser == null || _browser.IsClosed)63 await Init();64 //lets try a couple of times65 var delay = Backoff.ConstantBackoff(TimeSpan.FromMilliseconds(1000), retryCount: 5);66 var policy = Policy...

Full Screen

Full Screen

Program.cs

Source:Program.cs Github

copy

Full Screen

...65 BrowserURL = "http://127.0.0.1:9222"66 //BrowserURL = "http://192.168.4.180:9222"67 };68 var url = "https://www.google.com/";69 using (var browser = await PuppeteerSharp.Puppeteer.ConnectAsync(options))70 {71 using (var page = await browser.NewPageAsync())72 {73 await page.GoToAsync(url);74 var searchElm = await page.XPathAsync("//input[@name='q']");75 await searchElm[0].TypeAsync("hello world");76 await page.ScreenshotAsync(@"screenshot-remote.png");77 }78 browser.Disconnect();79 }80 Console.WriteLine("done!");81 }82 static async void RecaptchaUsage()83 {84 // Initialize recaptcha plugin with AntiCaptchaProvider85 var recaptchaPlugin = new RecaptchaPlugin(new TwoCaptcha("2captcha token"));86 var browser = await new PuppeteerExtra().Use(recaptchaPlugin).ConnectAsync(new ConnectOptions()87 {88 BrowserURL = "http://127.0.0.1:9222"89 });90 var page = await browser.NewPageAsync();91 await page.GoToAsync("https://patrickhlauke.github.io/recaptcha/");92 // Solves captcha in page!93 await recaptchaPlugin.SolveCaptchaAsync(page);94 Console.WriteLine("done");95 }96 }97}...

Full Screen

Full Screen

BrowserProvider.cs

Source:BrowserProvider.cs Github

copy

Full Screen

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

Full Screen

Full Screen

ConcurrentBrowserActivities.cs

Source:ConcurrentBrowserActivities.cs Github

copy

Full Screen

...22 var asm = Assembly.Load("Microsoft.Extensions.Options, Culture=neutral, PublicKeyToken=adb9793829ddae60");23 PuppeteerSharp.Browser browser = null;24 try25 {26 browser = await Puppeteer.ConnectAsync(new ConnectOptions { BrowserWSEndpoint = Constants.BrowserWSEndpoint });27 var page = await browser.NewPageAsync();28 await page.GoToAsync(url, new NavigationOptions { Timeout = 4000 });29 }30 catch (Exception ex)31 {32 return ex.Message;33 }34 finally35 {36 if (browser != null)37 {38 browser.Disconnect();39 }40 }...

Full Screen

Full Screen

Browser.cs

Source:Browser.cs Github

copy

Full Screen

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

Full Screen

Full Screen

ImageService.cs

Source:ImageService.cs Github

copy

Full Screen

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

Full Screen

Full Screen

ConnectAsync

Using AI Code Generation

copy

Full Screen

1var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false });2var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false, ExecutablePath = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe" });3var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false, ExecutablePath = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe", Args = new string[] { "--no-sandbox" } });4var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false, ExecutablePath = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe", Args = new string[] { "--no-sandbox", "--disable-setuid-sandbox" } });5var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false, ExecutablePath = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe", Args = new string[] { "--no-sandbox", "--disable-setuid-sandbox" }, DefaultViewport = new ViewPortOptions { Width = 1920, Height = 1080 } });6var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false, ExecutablePath = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe", Args = new string[] { "--no-sandbox", "--disable-setuid-sandbox" }, DefaultViewport = new ViewPortOptions { Width = 1920, Height = 1080 }, IgnoreHTTPSErrors = true });7var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless

Full Screen

Full Screen

ConnectAsync

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 public static async Task Main(string[] args)7 {8 var browser = await Puppeteer.ConnectAsync(new ConnectOptions9 {10 });11 var page = await browser.NewPageAsync();12 await page.GoToAsync(url);13 await page.PdfAsync("C:\\Users\\User\\Desktop\\2.pdf", new PdfOptions { Format = PaperFormat.A4 });14 await browser.CloseAsync();15 }16 }17}18using System;19using System.Threading.Tasks;20using PuppeteerSharp;21{22 {23 public static async Task Main(string[] args)24 {25 var browser = await Puppeteer.ConnectAsync(new ConnectOptions26 {27 });28 var page = await browser.NewPageAsync();29 await page.GoToAsync(url);30 await page.PdfAsync("C:\\Users\\User\\Desktop\\3.pdf", new PdfOptions { Format = PaperFormat.A4 });31 await browser.CloseAsync();32 }33 }34}35using System;36using System.Threading.Tasks;37using PuppeteerSharp;38{39 {40 public static async Task Main(string[] args)41 {42 var browser = await Puppeteer.ConnectAsync(new ConnectOptions43 {

Full Screen

Full Screen

ConnectAsync

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.ConnectAsync(new ConnectOptions9 {

Full Screen

Full Screen

ConnectAsync

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.ConnectAsync(options);11 var page = await browser.NewPageAsync();12 await page.ScreenshotAsync("google.png");13 await browser.CloseAsync();14 }15 }16}

Full Screen

Full Screen

ConnectAsync

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.ConnectAsync(new ConnectOptions9 {

Full Screen

Full Screen

ConnectAsync

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.ConnectAsync(new ConnectOptions9 {

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.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful