How to use string method of PuppeteerSharp.LaunchOptions class

Best Puppeteer-sharp code snippet using PuppeteerSharp.LaunchOptions.string

BrowserUtils.cs

Source:BrowserUtils.cs Github

copy

Full Screen

...9using System.IO.Compression;10namespace OutSystems.NssUltimatePDF.Browser11{12 public class BrowserUtils : IDisposable {13 private const string USER_AGENT_SUFFIX = "UltimatePDF/1.0";14 private PuppeteerSharp.Browser browser = null;15 private static BrowserFetcher BrowserFetcher {16 get {17 return new BrowserFetcher(new BrowserFetcherOptions() {18 Path = Path.Combine(Path.GetTempPath(), ".local-chromium")19 });20 }21 }22 private static string[] BrowserArgs {23 get {24 // Flags required for software rendering, since hardware acceleration is not available in session 025 return new string[] { "--disable-gpu", "--no-sandbox" };26 }27 }28 public static RevisionInfo RevisionInfo(int revision) {29 return BrowserFetcher.RevisionInfo(revision != 0 ? revision : BrowserFetcher.DefaultRevision);30 }31 public static bool IsValidRevision(RevisionInfo revision) {32 return File.Exists(revision.ExecutablePath);33 }34 public static IEnumerable<int> ValidLocalRevisions() {35 return BrowserFetcher.LocalRevisions().Where(r => IsValidRevision(RevisionInfo(r)));36 }37 public static async Task DownloadRevision(RevisionInfo revision) {38 if (Directory.Exists(revision.FolderPath) && !IsValidRevision(revision)) {39 Directory.Delete(revision.FolderPath, true);40 }41 await BrowserFetcher.DownloadAsync(revision.Revision);42 }43 public static void ExtractRevision(RevisionInfo revision, byte[] zip) {44 if (Directory.Exists(revision.FolderPath) && !IsValidRevision(revision)) {45 Directory.Delete(revision.FolderPath, true);46 }47 using (MemoryStream stream = new MemoryStream(zip)) {48 using (ZipArchive archive = new ZipArchive(stream, ZipArchiveMode.Read)) {49 foreach (var entry in archive.Entries) {50 if (string.IsNullOrEmpty(entry.Name)) {51 Directory.CreateDirectory(Path.Combine(revision.FolderPath, entry.FullName));52 } else {53 using (FileStream fileStream = File.Create(Path.Combine(revision.FolderPath, entry.FullName))) {54 using (Stream entryStream = entry.Open()) {55 entryStream.CopyTo(fileStream);56 }57 }58 }59 }60 }61 }62 if (Directory.Exists(revision.FolderPath) && !IsValidRevision(revision)) {63 throw new InvalidDataException("Could not find browser in " + revision.ExecutablePath);64 }65 }66 public async Task<byte[]> PrintPDF(string url, IEnumerable<CookieParam> cookies, ViewPortOptions viewport, PdfOptions options, RevisionInfo revision) {67 LaunchOptions launchOptions = new LaunchOptions() {68 ExecutablePath = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",69 Args = BrowserArgs,70 Headless = true,71 DefaultViewport = viewport,72 Timeout = 073 };74 browser = await Puppeteer.LaunchAsync(launchOptions);75 try {76 var page = await browser.NewPageAsync();77 try {78 WaitUntilNavigation[] waitUntilNavigations = { WaitUntilNavigation.Networkidle0 };79 NavigationOptions navigationOptions = new NavigationOptions() {80 Timeout = 0,81 WaitUntil = waitUntilNavigations82 };83 string originalUserAgent = await browser.GetUserAgentAsync();84 await page.SetUserAgentAsync($"{originalUserAgent} {USER_AGENT_SUFFIX}");85 if (cookies.Any()) {86 await page.SetCookieAsync(cookies.ToArray());87 }88 await page.GoToAsync(url, navigationOptions);89 await InjectCustomStylesAsync(page, ref options);90 91 bool hasPageNumbers = await page.EvaluateFunctionAsync<bool>("(window.UltimatePDF? window.UltimatePDF.hasPageNumbers : function() { return false; })");92 if (hasPageNumbers) {93 /*94 * When the layout has page numbers, we first retrieve a95 * first blank pdf to calculate the number of pages.96 * Then, knowing how many pages, we can layout the headers and footers,97 * and retrieve the final pdf.98 */99 byte[] blankContents = await page.PdfDataAsync(options);100 using (var blankPdf = new PDFUtils(blankContents)) {101 await page.EvaluateFunctionAsync("window.UltimatePDF.layoutPages", blankPdf.Pages);102 return await page.PdfDataAsync(options);103 }104 } else {105 return await page.PdfDataAsync(options);106 }107 } finally {108 await Cleanup(page);109 }110 } finally {111 Cleanup(browser);112 }113 }114 private Task InjectCustomStylesAsync(Page page, ref PdfOptions options) {115 /*116 * It seems that Puppeteer is not overriding the page styles from the print stylesheet.117 * As a workaround, we inject a <style> tag with the @page overrides at the end of <head>.118 * This issue might be eventually resolved in Puppeteer, and seems to be tracked by https://github.com/GoogleChrome/puppeteer/issues/393119 */120 string overrides = string.Empty;121 if (!options.PreferCSSPageSize && options.Width != null && options.Height != null) {122 overrides += $"size: {options.Width} {options.Height}; ";123 }124 if (options.MarginOptions.Top != null) {125 overrides += $"margin-top: {options.MarginOptions.Top}; ";126 }127 if (options.MarginOptions.Right != null) {128 overrides += $"margin-right: {options.MarginOptions.Right}; ";129 }130 if (options.MarginOptions.Bottom != null) {131 overrides += $"margin-bottom: {options.MarginOptions.Bottom}; ";132 }133 if (options.MarginOptions.Left != null) {134 overrides += $"margin-left: {options.MarginOptions.Left}; ";135 }136 if (!string.IsNullOrEmpty(overrides)) {137 /* Change the options so that Puppeteer respects our overrides */138 options.PreferCSSPageSize = true;139 options.Width = options.Height = null;140 options.MarginOptions = new MarginOptions();141 /* We must add the <style> tag at the end of <body> to make sure it is not overriden */142 string pageOverrides = "@page { " + overrides + "}";143 return page.EvaluateExpressionAsync($"const style = document.createElement('style'); style.innerHTML = '{pageOverrides}'; document.head.appendChild(style);");144 } else {145 return Task.CompletedTask;146 }147 }148 public async Task<byte[]> ScreenshotPNG(string url, IEnumerable<CookieParam> cookies, ViewPortOptions viewport, ScreenshotOptions options, RevisionInfo revision) {149 LaunchOptions launchOptions = new LaunchOptions() {150 ExecutablePath = revision.ExecutablePath,151 Args = BrowserArgs,152 Headless = true,153 DefaultViewport = viewport,154 Timeout = 0155 };156 browser = await Puppeteer.LaunchAsync(launchOptions);157 try {158 var page = await browser.NewPageAsync();159 try {160 NavigationOptions navigationOptions = new NavigationOptions() {161 Timeout = 0162 };163 string originalUserAgent = await browser.GetUserAgentAsync();164 await page.SetUserAgentAsync($"{originalUserAgent} {USER_AGENT_SUFFIX}");165 if (cookies.Any()) {166 await page.SetCookieAsync(cookies.ToArray());167 }168 await page.GoToAsync(url, navigationOptions);169 return await page.ScreenshotDataAsync(options);170 } finally {171 await Cleanup(page);172 }173 } finally {174 Cleanup(browser);175 }176 }177 public bool UserAgentMatches(string userAgent) {178 return userAgent.EndsWith($" {USER_AGENT_SUFFIX}");179 }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 }...

Full Screen

Full Screen

Methods.cs

Source:Methods.cs Github

copy

Full Screen

...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);63 var page = (await browser.PagesAsync()).First();64 SetPageAndFrame(data, page);65 await SetPageLoadingOptions(data, page);66 // Authenticate if the proxy requires auth67 if (data.UseProxy && data.Proxy is { NeedsAuthentication: true, Type: ProxyType.Http } proxy)68 await page.AuthenticateAsync(new Credentials { Username = proxy.Username, Password = proxy.Password });69 data.Logger.Log($"{(launchOptions.Headless ? "Headless " : "")}Browser opened successfully!", LogColors.DarkSalmon);70 }71 [Block("Closes an open puppeteer browser", name = "Close Browser")]72 public static async Task PuppeteerCloseBrowser(BotData data)73 {74 data.Logger.LogHeader();75 var browser = GetBrowser(data);76 await browser.CloseAsync();77 StopYoveProxyInternalServer(data);78 data.Logger.Log("Browser closed successfully!", LogColors.DarkSalmon);79 }80 [Block("Opens a new page in a new browser tab", name = "New Tab")]81 public static async Task PuppeteerNewTab(BotData data)82 {83 data.Logger.LogHeader();84 var browser = GetBrowser(data);85 var page = await browser.NewPageAsync();86 await SetPageLoadingOptions(data, page);87 SetPageAndFrame(data, page); // Set the new page as active88 data.Logger.Log($"Opened a new page", LogColors.DarkSalmon);89 }90 [Block("Closes the currently active browser tab", name = "Close Tab")]91 public static async Task PuppeteerCloseTab(BotData data)92 {93 data.Logger.LogHeader();94 var browser = GetBrowser(data);95 var page = GetPage(data);96 97 // Close the page98 await page.CloseAsync();99 100 // Set the first page as active101 page = (await browser.PagesAsync()).FirstOrDefault();102 SetPageAndFrame(data, page);103 if (page != null)104 await page.BringToFrontAsync();105 data.Logger.Log($"Closed the active page", LogColors.DarkSalmon);106 }107 [Block("Switches to the browser tab with a specified index", name = "Switch to Tab")]108 public static async Task PuppeteerSwitchToTab(BotData data, int index)109 {110 data.Logger.LogHeader();111 var browser = GetBrowser(data);112 var page = (await browser.PagesAsync())[index];113 await page.BringToFrontAsync();114 SetPageAndFrame(data, page);115 data.Logger.Log($"Switched to tab with index {index}", LogColors.DarkSalmon);116 }117 [Block("Reloads the current page", name = "Reload")]118 public static async Task PuppeteerReload(BotData data)119 {120 data.Logger.LogHeader();121 var page = GetPage(data);122 await page.ReloadAsync();123 SwitchToMainFramePrivate(data);124 data.Logger.Log($"Reloaded the page", LogColors.DarkSalmon);125 }126 [Block("Goes back to the previously visited page", name = "Go Back")]127 public static async Task PuppeteerGoBack(BotData data)128 {129 data.Logger.LogHeader();130 var page = GetPage(data);131 await page.GoBackAsync();132 SwitchToMainFramePrivate(data);133 data.Logger.Log($"Went back to the previously visited page", LogColors.DarkSalmon);134 }135 [Block("Goes forward to the next visited page", name = "Go Forward")]136 public static async Task PuppeteerGoForward(BotData data)137 {138 data.Logger.LogHeader();139 var page = GetPage(data);140 await page.GoForwardAsync();141 SwitchToMainFramePrivate(data);142 data.Logger.Log($"Went forward to the next visited page", LogColors.DarkSalmon);143 }144 private static PuppeteerSharp.Browser GetBrowser(BotData data)145 => data.TryGetObject<PuppeteerSharp.Browser>("puppeteer") ?? throw new Exception("The browser is not open!");146 private static PuppeteerSharp.Page GetPage(BotData data)147 => data.TryGetObject<PuppeteerSharp.Page>("puppeteerPage") ?? throw new Exception("No pages open!");148 private static void SwitchToMainFramePrivate(BotData data)149 => data.SetObject("puppeteerFrame", GetPage(data).MainFrame);150 private static void SetPageAndFrame(BotData data, PuppeteerSharp.Page page)151 {152 data.SetObject("puppeteerPage", page);153 SwitchToMainFramePrivate(data);154 }155 private static void StopYoveProxyInternalServer(BotData data)156 => data.TryGetObject<ProxyClient>("puppeteer.yoveproxy")?.Dispose();157 private static async Task SetPageLoadingOptions(BotData data, PuppeteerSharp.Page page)158 {159 await page.SetRequestInterceptionAsync(true);160 page.Request += (sender, e) =>161 {162 // If we only want documents and scripts but the resource is not one of those, block163 if (data.ConfigSettings.PuppeteerSettings.LoadOnlyDocumentAndScript && 164 e.Request.ResourceType != ResourceType.Document && e.Request.ResourceType != ResourceType.Script)165 {166 e.Request.AbortAsync();167 }168 // If the url contains one of the blocked urls169 else if (data.ConfigSettings.PuppeteerSettings.BlockedUrls170 .Where(u => !string.IsNullOrWhiteSpace(u))171 .Any(u => e.Request.Url.Contains(u, StringComparison.OrdinalIgnoreCase)))172 {173 e.Request.AbortAsync();174 }175 // Otherwise all good, continue176 else177 {178 e.Request.ContinueAsync();179 }180 };181 if (data.ConfigSettings.PuppeteerSettings.DismissDialogs)182 {183 page.Dialog += (sender, e) =>184 {...

Full Screen

Full Screen

SaveWebPage.xaml.cs

Source:SaveWebPage.xaml.cs Github

copy

Full Screen

1using CSharpCrawler.Util;2using System;3using System.Collections.Generic;4using System.IO;5using System.Linq;6using System.Text;7using System.Threading.Tasks;8using System.Windows;9using System.Windows.Controls;10using System.Windows.Data;11using System.Windows.Documents;12using System.Windows.Input;13using System.Windows.Media;14using System.Windows.Media.Imaging;15using System.Windows.Navigation;16using System.Windows.Shapes;17using ZT.Enhance;1819namespace CSharpCrawler.Views20{21 /// <summary>22 /// SaveWebPage.xaml 的交互逻辑23 /// </summary>24 public partial class SaveWebPage : Page25 {26 public SaveWebPage()27 {28 InitializeComponent();29 }303132 private async void btn_SaveAsImage_Click(object sender, RoutedEventArgs e)33 {34 //如果这一步发生异常了,可以参考 https://www.cnblogs.com/zhaotianff/p/13528507.html35 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}");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} ...

Full Screen

Full Screen

ApiFactory.cs

Source:ApiFactory.cs Github

copy

Full Screen

...18 }19 public async Task<List<Type>> Create(BrowserOptions configuration)20 {21 var executablePath = configuration?.ExecutablePath;22 var downloadBrowser = string.IsNullOrWhiteSpace(executablePath) && string.IsNullOrWhiteSpace(configuration?.BrowserWSEndpoint);23 if (downloadBrowser)24 {25 var path = GetBrowserPath();26 _logger.LogDebug("Downloading browser to path {Path}", path);27 28 var browserConfigurationFile = Path.Combine(path, ".browser.config");29 if (File.Exists(browserConfigurationFile))30 {31 executablePath = await File.ReadAllTextAsync(browserConfigurationFile, Encoding.UTF8);32 if (!File.Exists(executablePath))33 {34 File.Delete(browserConfigurationFile);35 Directory.Delete(path, true);36 executablePath = string.Empty;37 await Task.Delay(TimeSpan.FromMilliseconds(300));38 }39 }40 if (!File.Exists(browserConfigurationFile))41 {42 if (!Directory.Exists(path))43 {44 Directory.CreateDirectory(path);45 }46 var browserFetcherOptions = new BrowserFetcherOptions { Path = path };47 var browserFetcher = new BrowserFetcher(browserFetcherOptions);48 await browserFetcher.DownloadAsync(BrowserFetcher.DefaultRevision).ConfigureAwait(false);49 executablePath = browserFetcher.GetExecutablePath(BrowserFetcher.DefaultRevision);50 await File.WriteAllTextAsync(browserConfigurationFile, executablePath, Encoding.UTF8);51 await Task.Delay(TimeSpan.FromMilliseconds(300));52 }53 executablePath = await File.ReadAllTextAsync(browserConfigurationFile, Encoding.UTF8);54 }55 var code = string.Empty;56 if (!string.IsNullOrWhiteSpace(executablePath))57 {58 if (!File.Exists(executablePath))59 {60 throw new ArgumentException($"Can not use executable as the browser. File {executablePath} not found.");61 }62 _logger.LogDebug("Using locally installed Chromium based browser");63 var sourceWriter = new StringBuilder();64 sourceWriter.UsingNamespace("System.Threading.Tasks");65 sourceWriter.UsingNamespace("PuppeteerSharp");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(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 {100 return Path.Combine(Path.GetTempPath(), "ApiFramework_Browser");101 }102 }103}...

Full Screen

Full Screen

Program.cs

Source:Program.cs Github

copy

Full Screen

...5 class Program6 {7 static PuppeteerSharp.Browser browser;8 static PuppeteerSharp.Page browserPage;9 static Action<string> callbackFromBrowserDelegate;10 static string UserDataDirPath() =>11 System.IO.Path.Combine(Environment.GetEnvironmentVariable("LOCALAPPDATA"), "bot", "web-browser", "user-data");12 static void Main(string[] args)13 {14 /*15 2020-02-17 Observation before introducing the killing of previous web browser processes:16 LaunchAsync failed if a process from the last run was still present.17 (See report of this issue at https://forum.botengine.org/t/farm-manager-tribal-wars-2-farmbot/3038/32?u=viir)18 Unhandled exception. System.AggregateException: One or more errors occurred. (Failed to launch Chromium! [28592:33396:0217/074915.470:ERROR:cache_util_win.cc(21)] Unable to move the cache: Access is denied. (0x5)19 [28592:33396:0217/074915.471:ERROR:cache_util.cc(141)] Unable to move cache folder C:\Users\John\AppData\Local\bot\web-browser\user-data\ShaderCache\GPUCache to C:\Users\John\AppData\Local\bot\web-browser\user-data\ShaderCache\old_GPUCache_00020 [28592:33396:0217/074915.471:ERROR:disk_cache.cc(178)] Unable to create cache21 [28592:33396:0217/074915.471:ERROR:shader_disk_cache.cc(601)] Shader Cache Creation failed: -222 [28592:33396:0217/074915.473:ERROR:browser_gpu_channel_host_factory.cc(138)] Failed to launch GPU process.23 )24 ---> PuppeteerSharp.ChromiumProcessException: Failed to launch Chromium! [28592:33396:0217/074915.470:ERROR:cache_util_win.cc(21)] Unable to move the cache: Access is denied. (0x5)25 [28592:33396:0217/074915.471:ERROR:cache_util.cc(141)] Unable to move cache folder C:\Users\John\AppData\Local\bot\web-browser\user-data\ShaderCache\GPUCache to C:\Users\John\AppData\Local\bot\web-browser\user-data\ShaderCache\old_GPUCache_00026 [28592:33396:0217/074915.471:ERROR:disk_cache.cc(178)] Unable to create cache27 [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}...

Full Screen

Full Screen

PuppeteerBrowser.cs

Source:PuppeteerBrowser.cs Github

copy

Full Screen

...20 PuppeteerSharp.Browser browser = null;21 PuppeteerSharp.Page page = null;22 int width = 00;23 int height = 0;24 public string Name { get; set; } = null;25 public PuppeteerBrowser(string name = null)26 : this(1920, 1080, name)27 {28 }29 public PuppeteerBrowser(int displaywidth, int displayheight, string name = null)30 {31 this.width = displaywidth;32 this.height = displayheight;33 this.Name = "PuppeteerBrowser-" + (name ?? Devmasters.Core.TextUtil.GenRandomString(10));34 Init();35 }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;55 this.browser = Puppeteer.LaunchAsync(launchOptions).Result;56 this.page = browser.NewPageAsync().Result;57 logger.Info($"{this.Name}: Initiated PuppeteerBrowser");58 }59 object browserLock = new object();60 public PuppeteerSharp.Page Page()61 {62 return this.page;63 }64 public void WarmUp()65 {66 logger.Debug($"{this.Name}: Warming up");67 this.page.GoToAsync("https://www.google.com").Wait();...

Full Screen

Full Screen

DocumentsV2Controller.cs

Source:DocumentsV2Controller.cs Github

copy

Full Screen

...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) {31 Stopwatch stopwatch = Stopwatch.StartNew();32 stopwatch.Start();33 var files = await GeneratePdfAsync(fileStream.ToList(), landscape);34 return Ok(new { Paths = files.Select(x => "/pdf/" + x), Elapsed = stopwatch.ElapsedMilliseconds });35 }36 [NonAction]37 public async Task<List<string>> GeneratePdfAsync(List<IFormFile> streams, bool landscape) {38 s_browser ??= await Puppeteer.LaunchAsync(_browserOptions);39 var tasks = streams.Select(async x => {40 using (StreamReader stringReader = new StreamReader(x.OpenReadStream()))41 using (var page = await s_browser.NewPageAsync()) {42 await page.SetContentAsync(await stringReader.ReadToEndAsync());43 var fileName = $"{Guid.NewGuid()}.pdf";44 await page.PdfAsync($"{Directory.GetCurrentDirectory()}/files/{fileName}", new PdfOptions() { Format = PuppeteerSharp.Media.PaperFormat.A4, Landscape = landscape, OmitBackground = true, PrintBackground = true });45 return fileName;46 }47 });48 var files = await Task.WhenAll(tasks);49 return files.ToList();50 }51 [NonAction]52 public async Task<List<string>> GeneratePdfAsync(List<string> url, bool landscape) {53 s_browser ??= await Puppeteer.LaunchAsync(_browserOptions);54 var tasks = url.Select(async x => {55 using (var page = await s_browser.NewPageAsync()) {56 await page.GoToAsync(x);57 var fileName = $"{Guid.NewGuid()}.pdf";58 await page.PdfAsync($"{Directory.GetCurrentDirectory()}/files/{fileName}", new PdfOptions() { Format = PuppeteerSharp.Media.PaperFormat.A4, Landscape = landscape, OmitBackground = true, PrintBackground = true });59 return fileName;60 }61 });62 var files = await Task.WhenAll(tasks);63 return files.ToList();64 }65 }66}...

Full Screen

Full Screen

PuppeteerUtility.csx

Source:PuppeteerUtility.csx Github

copy

Full Screen

1#r "nuget:PuppeteerSharp, 1.18.0"2using PuppeteerSharp;3public static class PuppeteerUtility{4 private static string findChrome(){5 var chromeProcs = System.Diagnostics.Process.GetProcessesByName("chrome");6 if( !chromeProcs.Any()){7 throw new Exception("Chrome must be running for this code to find it");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];...

Full Screen

Full Screen

string

Using AI Code Generation

copy

Full Screen

1{2 {3 }4};5var browser = await Puppeteer.LaunchAsync(options);6var page = await browser.NewPageAsync();7await page.PdfAsync("google.pdf");8await browser.CloseAsync();9{10 {11 }12};13var browser = await Puppeteer.LaunchAsync(options);14var page = await browser.NewPageAsync();15await page.PdfAsync("google.pdf");16await browser.CloseAsync();17{18 {19 }20};21var browser = await Puppeteer.LaunchAsync(options);22var page = await browser.NewPageAsync();23await page.PdfAsync("google.pdf");24await browser.CloseAsync();25{26 {27 }28};29var browser = await Puppeteer.LaunchAsync(options);30var page = await browser.NewPageAsync();31await page.PdfAsync("google.pdf");32await browser.CloseAsync();33{34 {35 }36};37var browser = await Puppeteer.LaunchAsync(options);38var page = await browser.NewPageAsync();

Full Screen

Full Screen

string

Using AI Code Generation

copy

Full Screen

1{2 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",3 Args = new string[] { "--window-size=1920,1080" }4};5var browser = await Puppeteer.LaunchAsync(options);6var page = await browser.NewPageAsync();7await page.PdfAsync("google.pdf");8await browser.CloseAsync();9{10 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",11 Args = new string[] { "--window-size=1920,1080" }12};13var browser = await Puppeteer.LaunchAsync(options);14var page = await browser.NewPageAsync();15await page.PdfAsync("google.pdf");16await browser.CloseAsync();17{18 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",19 Args = new string[] { "--window-size=1920,1080" }20};21var browser = await Puppeteer.LaunchAsync(options);22var page = await browser.NewPageAsync();23await page.PdfAsync("google.pdf");24await browser.CloseAsync();25{26 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",27 Args = new string[] { "--window-size=1920,1080" }28};29var browser = await Puppeteer.LaunchAsync(options);30var page = await browser.NewPageAsync();31await page.PdfAsync("google.pdf");32await browser.CloseAsync();

Full Screen

Full Screen

string

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static void Main()7 {8 MainAsync().Wait();9 }10 static async Task MainAsync()11 {12 var browser = await Puppeteer.LaunchAsync(new LaunchOptions13 {14 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",15 });16 var page = await browser.NewPageAsync();17 await page.ScreenshotAsync("screenshot.png");18 await page.CloseAsync();19 await browser.CloseAsync();20 }21 }22}

Full Screen

Full Screen

string

Using AI Code Generation

copy

Full Screen

1var options = new LaunchOptions();2options.ExecutablePath = "/usr/bin/chromium";3options.Headless = true;4options.Args = new[] { "--no-sandbox", "--disable-setuid-sandbox" };5await Puppeteer.LaunchAsync(options);6var options = new LaunchOptions();7options.ExecutablePath = "/usr/bin/chromium";8options.Headless = true;9options.Args = new[] { "--no-sandbox", "--disable-setuid-sandbox" };10await Puppeteer.LaunchAsync(options);11var options = new LaunchOptions();12options.ExecutablePath = "/usr/bin/chromium";13options.Headless = true;14options.Args = new[] { "--no-sandbox", "--disable-setuid-sandbox" };15await Puppeteer.LaunchAsync(options);16var options = new LaunchOptions();17options.ExecutablePath = "/usr/bin/chromium";18options.Headless = true;19options.Args = new[] { "--no-sandbox", "--disable-setuid-sandbox" };20await Puppeteer.LaunchAsync(options);21var options = new LaunchOptions();22options.ExecutablePath = "/usr/bin/chromium";23options.Headless = true;24options.Args = new[] { "--no-sandbox", "--disable-setuid-sandbox" };25await Puppeteer.LaunchAsync(options);26var options = new LaunchOptions();27options.ExecutablePath = "/usr/bin/chromium";28options.Headless = true;29options.Args = new[] { "--no-sandbox", "--disable-setuid-sandbox" };30await Puppeteer.LaunchAsync(options);31var options = new LaunchOptions();32options.ExecutablePath = "/usr/bin/chromium";33options.Headless = true;34options.Args = new[] { "--no-sandbox", "--disable-setuid-sandbox" };35await Puppeteer.LaunchAsync(options);

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 LaunchOptions

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful