Best Puppeteer-sharp code snippet using PuppeteerSharp.LaunchOptions
Methods.cs
Source:Methods.cs
...44 args += $" --proxy-server={proxyClient.GetProxy(null).Authority}";45 }46 }47 // Configure the options48 var launchOptions = new LaunchOptions49 {50 Args = new string[] { args },51 ExecutablePath = data.Providers.PuppeteerBrowser.ChromeBinaryLocation,52 Headless = data.ConfigSettings.PuppeteerSettings.Headless,53 DefaultViewport = null // This is important54 };55 // Add the plugins56 var extra = new PuppeteerExtra();57 extra.Use(new StealthPlugin());58 // Launch the browser59 var browser = await extra.LaunchAsync(launchOptions);60 browser.IgnoreHTTPSErrors = data.ConfigSettings.PuppeteerSettings.IgnoreHttpsErrors;61 // Save the browser for further use62 data.SetObject("puppeteer", browser);...
SaveWebPage.xaml.cs
Source:SaveWebPage.xaml.cs
...35 try36 {37 await new PuppeteerSharp.BrowserFetcher().DownloadAsync(PuppeteerSharp.BrowserFetcher.DefaultRevision);3839 var browser = await PuppeteerSharp.Puppeteer.LaunchAsync(new PuppeteerSharp.LaunchOptions40 {41 Headless = true42 });4344 var page = await browser.NewPageAsync(); //æå¼ä¸ä¸ªæ°æ ç¾45 await page.GoToAsync(this.tbox_Url.Text); //访é®é¡µé¢4647 //设置æªå¾é项48 PuppeteerSharp.ScreenshotOptions screenshotOptions = new PuppeteerSharp.ScreenshotOptions();49 //screenshotOptions.Clip = new PuppeteerSharp.Media.Clip() { Height = 0, Width = 0, X = 0, Y = 0 };//设置æªåªåºå50 screenshotOptions.FullPage = true; //æ¯å¦æªåæ´ä¸ªé¡µé¢51 screenshotOptions.OmitBackground = false;//æ¯å¦ä½¿ç¨éæèæ¯ï¼èä¸æ¯é»è®¤ç½è²èæ¯52 screenshotOptions.Quality = 100; //æªå¾è´¨é 0-100ï¼pngä¸å¯ç¨ï¼53 screenshotOptions.Type = PuppeteerSharp.ScreenshotType.Jpeg; //æªå¾æ ¼å¼5455 var fileName = Environment.CurrentDirectory + $"\\download\\{await page.GetTitleAsync()}.jpg";5657 if (System.IO.File.Exists(fileName))58 {59 fileName = fileName.Replace(".jpg", $"{DateTime.Now.ToString("ffff")}.jpg");60 }6162 await page.ScreenshotAsync(fileName, screenshotOptions);6364 if (System.IO.File.Exists(fileName))65 {66 BitmapImage bi = new BitmapImage();67 bi.BeginInit();68 bi.UriSource = new Uri(fileName, UriKind.Absolute);69 bi.EndInit();70 this.image.Source = bi;71 }72 else73 {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}");107
...
ApiFactory.cs
Source:ApiFactory.cs
...66 sourceWriter.Namespace("Weikio.ApiFramework.Plugins.Browser");67 sourceWriter.StartClass($"ExecutableBrowser : WebBrowser");68 sourceWriter.WriteLine($"private readonly string _executablePath = @\"{executablePath}\";");69 sourceWriter.Write(70 "protected override async Task<PuppeteerSharp.Browser> GetBrowser() { var launchOptions = new LaunchOptions() { Headless = true, ExecutablePath = _executablePath };var result = await Puppeteer.LaunchAsync(launchOptions); return result; }");71 sourceWriter.FinishBlock(); // Finish the class72 sourceWriter.FinishBlock(); // Finish the namespace73 code = sourceWriter.ToString();74 }75 else76 {77 _logger.LogDebug("Using remote browser");78 var sourceWriter = new StringBuilder();79 sourceWriter.UsingNamespace("System.Threading.Tasks");80 sourceWriter.UsingNamespace("PuppeteerSharp");81 sourceWriter.Namespace("Weikio.ApiFramework.Plugins.Browser");82 sourceWriter.StartClass($"RemoteBrowser : WebBrowser");83 sourceWriter.WriteLine($"private readonly string _browserWSEndpoint = \"{configuration?.BrowserWSEndpoint}\";");84 sourceWriter.Write(...
Form1.cs
Source:Form1.cs
...19 }20 private async void button1_Click(object sender, EventArgs e)21 { 22 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);23 browser = await Puppeteer.LaunchAsync(new LaunchOptions24 {25 Headless = true26 });27 //å¦æawait new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);æ§è¡ä¸æå28 //å¯ä»¥æå¨è®¿é®https://commondatastorage.googleapis.com/chromium-browser-snapshots/index.html?prefix=Win_x64/ï¼ä¸è½½Chromiumæµè§å¨ï¼å¹¶è§£åå°æå®ä½ç½®29 //åéè¿ä»¥ä¸ä»£ç åå§å30 /*31 * LaunchOptions options = new LaunchOptions();32 options.Headless = true;33 options.DefaultViewport = null;34 //忽ç¥è¯ä¹¦é误35 options.IgnoreHTTPSErrors = true;36 //chromePathå°±æ¯ä¸è½½çChromiumæµè§å¨è§£åçä½ç½® 37 options.ExecutablePath = chromePath;38 browser = await Puppeteer.LaunchAsync(options);39 */40 var page = await browser.NewPageAsync();41 await page.GoToAsync(this.textBox1.Text);42 var html = await page.GetContentAsync();43 this.richTextBox1.Text = html;44 }45 private async void button2_Click(object sender, EventArgs e)...
Program.cs
Source:Program.cs
...27 [28592:33396:0217/074915.471:ERROR:shader_disk_cache.cc(601)] Shader Cache Creation failed: -228 [28592:33396:0217/074915.473:ERROR:browser_gpu_channel_host_factory.cc(138)] Failed to launch GPU process.29 at PuppeteerSharp.ChromiumProcess.State.StartingState.StartCoreAsync(ChromiumProcess p)30 at PuppeteerSharp.ChromiumProcess.State.StartingState.StartCoreAsync(ChromiumProcess p)31 at PuppeteerSharp.Launcher.LaunchAsync(LaunchOptions options)32 at PuppeteerSharp.Launcher.LaunchAsync(LaunchOptions options)33 */34 KillPreviousWebBrowserProcesses();35 StartWebBrowser().Wait();36 }37 static void KillPreviousWebBrowserProcesses()38 {39 var matchingProcesses =40 System.Diagnostics.Process.GetProcesses()41 /*42 2020-02-1743 .Where(process => process.StartInfo.Arguments.Contains(UserDataDirPath(), StringComparison.InvariantCultureIgnoreCase))44 */45 .Where(ProcessIsWebBrowser)46 .ToList();47 foreach (var process in matchingProcesses)48 {49 if (process.HasExited)50 continue;51 process.Kill();52 }53 }54 static bool ProcessIsWebBrowser(System.Diagnostics.Process process)55 {56 try57 {58 return process.MainModule.FileName.Contains(".local-chromium");59 }60 catch61 {62 return false;63 }64 }65 static async System.Threading.Tasks.Task StartWebBrowser()66 {67 await new PuppeteerSharp.BrowserFetcher().DownloadAsync(PuppeteerSharp.BrowserFetcher.DefaultRevision);68 browser = await PuppeteerSharp.Puppeteer.LaunchAsync(new PuppeteerSharp.LaunchOptions69 {70 Headless = false,71 UserDataDir = UserDataDirPath(),72 DefaultViewport = null,73 });74 browserPage = (await browser.PagesAsync()).FirstOrDefault() ?? await browser.NewPageAsync();75 await browserPage.ExposeFunctionAsync("____callback____", (string returnValue) =>76 {77 callbackFromBrowserDelegate?.Invoke(returnValue);78 return 0;79 });80 }81 }82}...
PuppeteerBrowser.cs
Source:PuppeteerBrowser.cs
...36 private void Init()37 {38 logger.Debug($"{this.Name}: Initiating PuppeteerBrowser");39 var chromeBinaryFileName = Devmasters.Core.Util.Config.GetConfigValue("ChromeBinaryFullPath");40 var launchOptions = new LaunchOptions()41 {42 Headless = true,43 DefaultViewport = new ViewPortOptions()44 {45 DeviceScaleFactor = 1,46 IsLandscape = false,47 HasTouch = false,48 IsMobile = false,49 Height = this.height,50 Width = this.width,51 }52 };53 if (!string.IsNullOrEmpty(chromeBinaryFileName))54 launchOptions.ExecutablePath = chromeBinaryFileName;...
DocumentsV2Controller.cs
Source:DocumentsV2Controller.cs
...11namespace PdfService.Controllers {12 [ApiController]13 [Route("[controller]")]14 public class DocumentsV2Controller: ControllerBase {15 //private readonly LaunchOptions _browserOptions = new LaunchOptions { Headless = true, ExecutablePath = @"C:\Users\Zeroget\Downloads\chrome-win\chrome-win\chrome.exe", Args = new string[] { "--no-sandbox" } };16 private readonly LaunchOptions _browserOptions = new LaunchOptions { Headless = true, ExecutablePath = @"/usr/bin/chromium-browser", Args = new string[] { "--no-sandbox" } };17 private static Browser s_browser = null;18 private readonly ILogger<DocumentsV2Controller> _logger;19 public DocumentsV2Controller(ILogger<DocumentsV2Controller> logger) {20 _logger = logger;21 }22 [HttpPost("byUrl")]23 public async Task<IActionResult> Get(List<string> url, bool landscape) {24 Stopwatch stopwatch = Stopwatch.StartNew();25 stopwatch.Start();26 var files = await GeneratePdfAsync(url, landscape);27 return Ok(new { Paths = files.Select(x => "/pdf/" + x), Elapsed = stopwatch.ElapsedMilliseconds });28 }29 [HttpPost("byFile")]30 public async Task<IActionResult> Post(IFormFileCollection fileStream, bool landscape) {...
PuppeteerUtility.csx
Source:PuppeteerUtility.csx
...8 }9 return chromeProcs.First().Modules[0].FileName;10 }11 public async static Task<PageResult> GetPage(){12 var browser = await Puppeteer.LaunchAsync(new LaunchOptions13 {14 Headless = false,15 ExecutablePath = findChrome(),16 Args = new[]{ "--app=http://localhost/null" }17 });18 var page = (await browser.PagesAsync())[0];19 //await page.WaitForNavigationAsync();20 return new PageResult{21 Browser = browser, // they may need the browser to close it after they are done22 Page = page23 };24 }25 26}...
LaunchOptions
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static async Task Main(string[] args)7 {8 {9 Args = new[] { "--no-sandbox" }10 };11 using (var browser = await Puppeteer.LaunchAsync(options))12 using (var page = await browser.NewPageAsync())13 {14 await page.ScreenshotAsync("google.png");15 }16 }17 }18}19using System;20using System.Threading.Tasks;21using PuppeteerSharp;22{23 {24 static async Task Main(string[] args)25 {26 {27 Args = new[] { "--no-sandbox" }28 };29 using (var browser = await Puppeteer.LaunchAsync(options))30 using (var page = await browser.NewPageAsync())31 {32 await page.ScreenshotAsync("google.png");33 }34 }35 }36}37using System;38using System.Threading.Tasks;39using PuppeteerSharp;40{41 {42 static async Task Main(string[] args)43 {44 {45 Args = new[] { "--no-sandbox" }46 };47 using (var browser = await Puppeteer.LaunchAsync(options))48 using (var page = await browser.NewPageAsync())49 {50 await page.ScreenshotAsync("google.png");51 }52 }53 }54}55using System;56using System.Threading.Tasks;57using PuppeteerSharp;58{59 {60 static async Task Main(string[] args)61 {62 {63 Args = new[] { "--no-sandbox
LaunchOptions
Using AI Code Generation
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 Args = new[] { "--disable-gpu" }11 };12 using (var browser = await Puppeteer.LaunchAsync(options))13 using (var page = await browser.NewPageAsync())14 {15 await page.ScreenshotAsync("google.png");16 }17 }18 }19}20using System;21using System.Threading.Tasks;22using PuppeteerSharp;23{24 {25 static async Task Main(string[] args)26 {27 {28 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",29 Args = new[] { "--disable-gpu" }30 };31 using (var browser = await Puppeteer.LaunchAsync
LaunchOptions
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 {13 Args = new string[] { "--window-size=1920,1080" }14 };15 using (var browser = await Puppeteer.LaunchAsync(options))16 {17 using (var page = await browser.NewPageAsync())18 {19 await page.ScreenshotAsync("google.png");20 }21 }22 }23 }24}25at PuppeteerSharp.Launcher.LaunchAsync(LaunchOptions options) in26at PuppeteerSharp.Launcher.LaunchAsync(LaunchOptions options) in27at PuppeteerSharp.Launcher.LaunchAsync(LaunchOptions options) in28at PuppeteerSharp.Launcher.LaunchAsync(LaunchOptions options) in29at PuppeteerSharp.Launcher.LaunchAsync(LaunchOptions options) in30at PuppeteerSharp.Launcher.LaunchAsync(LaunchOptions options) in31at PuppeteerSharp.Launcher.LaunchAsync(LaunchOptions options) in32at PuppeteerSharp.Launcher.LaunchAsync(LaunchOptions options) in
LaunchOptions
Using AI Code Generation
1using System.Threading.Tasks;2using PuppeteerSharp;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 }12 }13}
LaunchOptions
Using AI Code Generation
1using System;2using System.IO;3using System.Threading.Tasks;4using PuppeteerSharp;5{6 {7 static async Task Main(string[] args)8 {9 {10 Args = new string[] { "--disable-notifications" }11 };12 using (var browser = await Puppeteer.LaunchAsync(options))13 {14 var page = await browser.NewPageAsync();15 var title = await page.EvaluateExpressionAsync<string>("document.title");16 Console.WriteLine(title);17 await page.ScreenshotAsync(Path.Combine(Directory.GetCurrentDirectory(), "example.png"));18 }19 }20 }21}
LaunchOptions
Using AI Code Generation
1using PuppeteerSharp;2{3 {4 public string[] Args { get; set; }5 public string[] IgnoreDefaultArgs { get; set; }6 public bool IgnoreHTTPSErrors { get; set; }7 public bool Headless { get; set; }8 public string ExecutablePath { get; set; }9 public bool SlowMo { get; set; }10 public bool Dumpio { get; set; }11 public bool Devtools { get; set; }12 public bool HandleSIGINT { get; set; }13 public bool HandleSIGTERM { get; set; }14 public bool HandleSIGHUP { get; set; }15 public bool Timeout { get; set; }16 public bool DefaultViewport { get; set; }17 public bool Args { get; set; }18 public bool IgnoreDefaultArgs { get; set; }19 public bool IgnoreHTTPSErrors { get; set; }20 public bool Headless { get; set; }21 public bool ExecutablePath { get; set; }22 public bool SlowMo { get; set; }23 public bool Dumpio { get; set; }24 public bool Devtools { get; set; }25 public bool HandleSIGINT { get; set; }26 public bool HandleSIGTERM { get; set; }27 public bool HandleSIGHUP { get; set; }28 public bool Timeout { get; set; }29 public bool DefaultViewport { get; set; }30 public bool Args { get; set; }31 public bool IgnoreDefaultArgs { get; set; }32 public bool IgnoreHTTPSErrors { get; set; }33 public bool Headless { get; set; }34 public bool ExecutablePath { get; set; }35 public bool SlowMo { get; set; }36 public bool Dumpio { get; set; }37 public bool Devtools { get; set; }38 public bool HandleSIGINT { get; set; }39 public bool HandleSIGTERM { get; set; }40 public bool HandleSIGHUP { get; set; }41 public bool Timeout { get; set; }42 public bool DefaultViewport { get; set; }43 public bool Args { get; set; }44 public bool IgnoreDefaultArgs { get;
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!!