Best Puppeteer-sharp code snippet using PuppeteerSharp.Browser.Disconnect
FetchDynamicResource.xaml.cs
Source:FetchDynamicResource.xaml.cs
...357358 var html = await page.GetContentAsync();359360 //å
³éæµè§å¨361 browser.Disconnect();362 browser.Dispose();363 ShowStatusTextPuppeteer("就绪");364 return html;365 }366367 private void ShowStatusTextPuppeteer(string text)368 {369 this.Dispatcher.Invoke(() => {370 this.lbl_StatusText_Puppeteer.Content = text;371 });372 }373 #endregion374375
...
BrowserUtils.cs
Source:BrowserUtils.cs
...180 private async Task Cleanup(Page page) {181 await page.CloseAsync();182 }183 private void Cleanup(PuppeteerSharp.Browser browser) {184 browser.Disconnect();185 Dispose();186 }187 public void Dispose() {188 if (browser != null) {189 ProcessUtils.KillProcessTree(browser.Process);190 }191 }192 }193}...
WorkerActivities.cs
Source:WorkerActivities.cs
...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(143 // [ActivityTrigger] DurableActivityContext ctx,144 // TraceWriter log )145 // {146 // var workerid = "AAAA";147 // var workerargsjson = ctx.GetInput<string>();148 // log.Warning(workerargsjson);149 // var workerargs = JsonConvert.DeserializeObject<Model.WorkerArgs>(workerargsjson);150 // var asm = Assembly.Load("Microsoft.Extensions.Options, Culture=neutral, PublicKeyToken=adb9793829ddae60");151 // PuppeteerSharp.Browser browser = null;152 // try153 // {154 // // await workerargs.Action.RunAsync(workerargs.Page);155 // }156 // catch (Exception ex)157 // {158 // return new Model.WorkerResult() { WorkerId= workerid, Success=false };159 // }160 // finally161 // {162 // if (browser != null)163 // {164 // browser.Disconnect();165 // }166 // }167 // return new Model.WorkerResult() { WorkerId= workerid, Success=true };168 // }169 // [FunctionName("A_TestSingle")]170 // public static async Task<string> TestSingle(171 // [ActivityTrigger] DurableActivityContext ctx,172 // TraceWriter log)173 // {174 // var workerid = "AAAA";175 // var workerargsjson = ctx.GetInput<string>();176 // log.Warning(workerargsjson);177 // PuppeteerSharp.Browser browser = null;178 // try...
SaveWebPage.xaml.cs
Source:SaveWebPage.xaml.cs
...74 EMessageBox.Show("ä¿åç½é¡µæªå¾å¤±è´¥");75 }7677 //å¨æåè®°å¾å
³éæµè§å¨åéæ¾èµæº78 browser.Disconnect();79 browser.Dispose();80 }81 catch(Exception ex)82 {83 EMessageBox.Show(ex.Message);84 }85 }8687 private async void btn_SaveAsPDF_Click(object sender, RoutedEventArgs e)88 {89 //æå¼ç½é¡µçæä½è·ä¸é¢æ¯ä¸æ ·ç90 try91 {92 await new PuppeteerSharp.BrowserFetcher().DownloadAsync(PuppeteerSharp.BrowserFetcher.DefaultRevision);93 var browser = await PuppeteerSharp.Puppeteer.LaunchAsync(new PuppeteerSharp.LaunchOptions94 {95 Headless = true96 });97 var page = await browser.NewPageAsync(); //æå¼ä¸ä¸ªæ°æ ç¾98 await page.GoToAsync(this.tbox_Url.Text); //访é®é¡µé¢99100 //设置PDFé项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 {121 fileName = fileName.Replace(".pdf", $"{DateTime.Now.ToString("ffff")}.pdf");122 }123124 //ä¿åPDF125 await page.PdfAsync(fileName, pdfOptions);126 EMessageBox.Show($"{fileName}ä¿åæå");127128 //å¨æåè®°å¾å
³éæµè§å¨åéæ¾èµæº129 browser.Disconnect();130 browser.Dispose();131 }132 catch(Exception ex)133 {134 EMessageBox.Show(ex.Message);135 }136 }137 }138}
...
Program.cs
Source:Program.cs
...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!...
ChromiumHelper.cs
Source:ChromiumHelper.cs
...126 {127 if (browser != null)128 {129 await browser.CloseAsync();130 browser.Disconnect();131 browser.Dispose(); 132 }133 }134 }135}...
BrowserDisconnectTests.cs
Source:BrowserDisconnectTests.cs
...5using Xunit.Abstractions;6namespace PuppeteerSharp.Tests.LauncherTests7{8 [Collection(TestConstants.TestFixtureCollectionName)]9 public class BrowserDisconnectTests : PuppeteerBrowserBaseTest10 {11 public BrowserDisconnectTests(ITestOutputHelper output) : base(output)12 {13 }14 [PuppeteerTest("launcher.spec.ts", "Browser.disconnect", "should reject navigation when browser closes")]15 [PuppeteerFact]16 public async Task ShouldRejectNavigationWhenBrowserCloses()17 {18 Server.SetRoute("/one-style.css", _ => Task.Delay(10000));19 await using (var browser = await Puppeteer.LaunchAsync(TestConstants.DefaultBrowserOptions()))20 {21 var remote = await Puppeteer.ConnectAsync(new ConnectOptions22 {23 BrowserWSEndpoint = browser.WebSocketEndpoint24 });25 var page = await remote.NewPageAsync();26 var navigationTask = page.GoToAsync(TestConstants.ServerUrl + "/one-style.html", new NavigationOptions27 {28 Timeout = 6000029 });30 await Server.WaitForRequest("/one-style.css");31 remote.Disconnect();32 var exception = await Assert.ThrowsAsync<NavigationException>(() => navigationTask);33 Assert.Contains("Navigation failed because browser has disconnected!", exception.Message);34 }35 }36 [PuppeteerTest("launcher.spec.ts", "Browser.disconnect", "should reject waitForSelector when browser closes")]37 [PuppeteerFact]38 public async Task ShouldRejectWaitForSelectorWhenBrowserCloses()39 {40 Server.SetRoute("/empty.html", _ => Task.Delay(10000));41 await using (var browser = await Puppeteer.LaunchAsync(TestConstants.DefaultBrowserOptions()))42 {43 var remote = await Puppeteer.ConnectAsync(new ConnectOptions44 {45 BrowserWSEndpoint = browser.WebSocketEndpoint46 });47 var page = await remote.NewPageAsync();48 var watchdog = page.WaitForSelectorAsync("div", new WaitForSelectorOptions { Timeout = 60000 });49 remote.Disconnect();50 var exception = await Assert.ThrowsAsync<TargetClosedException>(() => watchdog);51 Assert.Equal("Connection disposed", exception.CloseReason);52 }53 }54 }55}...
ConcurrentBrowserActivities.cs
Source:ConcurrentBrowserActivities.cs
...34 finally35 {36 if (browser != null)37 {38 browser.Disconnect();39 }40 }41 return $"Processed {url} shit all.";42 }43 [FunctionName("A_Worker")]44 public static async Task<string> Worker(45 [ActivityTrigger] DurableActivityContext ctx,46 TraceWriter log47 )48 {49 return "";50 }51 }52 public static class Constants...
Disconnect
Using AI Code Generation
1using PuppeteerSharp;2using System;3using System.Threading.Tasks;4{5 {6 static async Task Main(string[] args)7 {8 var browser = await Puppeteer.LaunchAsync(new LaunchOptions9 {10 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"11 });12 var page = await browser.NewPageAsync();13 await page.WaitForSelectorAsync("input[title='Search']");14 await page.TypeAsync("input[title='Search']", "PuppeteerSharp");15 await page.ClickAsync("input[value='Google Search']");16 await page.WaitForSelectorAsync("a[href='
Disconnect
Using AI Code Generation
1using PuppeteerSharp;2using System.Threading.Tasks;3{4 {5 static async Task Main(string[] args)6 {7 var browser = await Puppeteer.LaunchAsync(new LaunchOptions8 {9 });10 var page = await browser.NewPageAsync();11 await page.ScreenshotAsync("google1.png");12 await browser.DisconnectAsync();13 }14 }15}
Disconnect
Using AI Code Generation
1using PuppeteerSharp;2using System;3using System.Threading.Tasks;4{5 {6 static void Main(string[] args)7 {8 MainAsync().Wait();9 }10 static async Task MainAsync()11 {12 var browser = await Puppeteer.LaunchAsync(new LaunchOptions13 {14 });15 var page = await browser.NewPageAsync();16 await page.WaitForSelectorAsync("input[name='q']");17 await page.TypeAsync("input[name='q']", "PuppeteerSharp");18 await page.ClickAsync("input[value='Google Search']");19 await page.WaitForTimeoutAsync(1000);20 await browser.DisconnectAsync();21 }22 }23}
Disconnect
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static void Main(string[] args)7 {8 {9 MainAsync().Wait();10 }11 catch (Exception e)12 {13 Console.WriteLine(e.Message);14 }15 }16 static async Task MainAsync()17 {18 var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });19 await browser.DisconnectAsync();20 }21 }22}23Related Posts: PuppeteerSharp - How to use CloseAsync() method24PuppeteerSharp - How to use LaunchAsync() method25PuppeteerSharp - How to use NewPageAsync() method26PuppeteerSharp - How to use NewPageAsync() method27PuppeteerSharp - How to use NewPageAsync() method28PuppeteerSharp - How to use LaunchAsync() method29PuppeteerSharp - How to use NewPageAsync() method
Disconnect
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4using System.Threading;5{6 {7 public static void Main(string[] args) => MainAsync().GetAwaiter().GetResult();8 public static async Task MainAsync()9 {10 var browser = await Puppeteer.LaunchAsync(new LaunchOptions11 {12 });13 var page = await browser.NewPageAsync();14 await page.ScreenshotAsync("google.png");15 await browser.DisconnectAsync();16 Console.WriteLine("Browser disconnected");17 }18 }19}20C# | PuppeteerSharp - BrowserFetcher.DownloadAsync() Method21C# | PuppeteerSharp - BrowserFetcher.CanDownloadAsync() Method22C# | PuppeteerSharp - BrowserFetcher.LocalRevisions() Method23C# | PuppeteerSharp - BrowserFetcher.RemoveAsync() Method
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!!