How to use Puppeteer class of PuppeteerSharp package

Best Puppeteer-sharp code snippet using PuppeteerSharp.Puppeteer

Methods.cs

Source:Methods.cs Github

copy

Full Screen

1using Yove.Proxy;2using PuppeteerExtraSharp;3using PuppeteerExtraSharp.Plugins.ExtraStealth;4using PuppeteerSharp;5using RuriLib.Attributes;6using RuriLib.Logging;7using RuriLib.Models.Bots;8using System;9using System.Collections.Generic;10using System.Linq;11using System.Threading.Tasks;12using ProxyType = RuriLib.Models.Proxies.ProxyType;13namespace RuriLib.Blocks.Puppeteer.Browser14{15 [BlockCategory("Browser", "Blocks for interacting with a puppeteer browser", "#e9967a")]16 public static class Methods17 {18 [Block("Opens a new puppeteer browser", name = "Open Browser")]19 public static async Task PuppeteerOpenBrowser(BotData data)20 {21 data.Logger.LogHeader();22 // Check if there is already an open browser23 var oldBrowser = data.TryGetObject<PuppeteerSharp.Browser>("puppeteer");24 if (oldBrowser is not null && !oldBrowser.IsClosed)25 {26 data.Logger.Log("The browser is already open, close it if you want to open a new browser", LogColors.DarkSalmon);27 return;28 }29 var args = data.ConfigSettings.PuppeteerSettings.CommandLineArgs;30 if (data.Proxy != null && data.UseProxy)31 {32 if (data.Proxy.Type == ProxyType.Http || !data.Proxy.NeedsAuthentication)33 {34 args += $" --proxy-server={data.Proxy.Type.ToString().ToLower()}://{data.Proxy.Host}:{data.Proxy.Port}";35 }36 else37 {38 var proxyType = data.Proxy.Type == ProxyType.Socks5 ? Yove.Proxy.ProxyType.Socks5 : Yove.Proxy.ProxyType.Socks4;39 var proxyClient = new ProxyClient(40 data.Proxy.Host, data.Proxy.Port,41 data.Proxy.Username, data.Proxy.Password, 42 proxyType);43 data.SetObject("puppeteer.yoveproxy", proxyClient);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);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 {185 data.Logger.Log($"Dialog automatically dismissed: {e.Dialog.Message}", LogColors.DarkSalmon);186 e.Dialog.Dismiss();187 };188 }189 }190 }191}...

Full Screen

Full Screen

SaveWebPage.xaml.cs

Source:SaveWebPage.xaml.cs Github

copy

Full Screen

...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}保存成功");127 ...

Full Screen

Full Screen

ApiFactory.cs

Source:ApiFactory.cs Github

copy

Full Screen

...4using System.Linq;5using System.Text;6using System.Threading.Tasks;7using Microsoft.Extensions.Logging;8using PuppeteerSharp;9using Weikio.TypeGenerator;10namespace Weikio.ApiFramework.Plugins.Browser11{12 public class ApiFactory13 {14 private readonly ILogger<ApiFactory> _logger;15 public ApiFactory(ILogger<ApiFactory> logger)16 {17 _logger = logger;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

GistGithubService.cs

Source:GistGithubService.cs Github

copy

Full Screen

...9 class GistGithubService : IGistGithubService10 {11 private readonly GitHubClient client =12 new GitHubClient(new ProductHeaderValue("Patrick-Star-Helper"));13 private readonly PuppeteerSharp.BrowserFetcher browserFetcher =14 new PuppeteerSharp.BrowserFetcher();15 private readonly GitHubModel gitHubModel;16 public bool IsAuthenticated { get; private set; }17 private readonly ICredentialStore credentialStore;18 public GistGithubService(19 IAppConfigProvider configProvider,20 ICredentialStore credentialStore)21 {22 this.credentialStore = credentialStore;23 gitHubModel = configProvider.Configuration.GitHub!;24 browserFetcher.DownloadProgressChanged += Fetcher_DownloadProgressChanged;25 }26 private void Fetcher_DownloadProgressChanged(object sender, System.Net.DownloadProgressChangedEventArgs e)27 {28 Console.WriteLine("Downloading Chromium: {0}%", e.ProgressPercentage);29 }30 public async Task<bool> Authenticate()31 {32 var accessToken = await credentialStore.LoadAccessToken();33 //if (!string.IsNullOrEmpty(accessToken))34 //{35 // IsAuthenticated = true;36 // client.Credentials = new Credentials(accessToken);37 // return true;38 //}39 var loginRequest = new OauthLoginRequest(gitHubModel.ClientId);40 foreach (var scope in gitHubModel.Scopes!)41 loginRequest.Scopes.Add(scope);42 var redirectPage = client.Oauth.GetGitHubLoginUrl(loginRequest);43 client.Credentials = await FetchGitCredential(redirectPage);44 await credentialStore.StoreAccessToken(client.Credentials.GetToken());45 IsAuthenticated = true;46 return true;47 }48 public async Task<string?> Create(GistModel gist)49 {50 try51 {52 var result = await client.Gist.Create(new NewGist53 {54 Files =55 {56 [gist.Name] = gist.Content57 },58 Description = gist.Description59 });60 return result?.Id;61 }62 catch (Exception ex)63 {64 var msg = ex.Message;65 throw;66 }67 }68 public async Task<string?> Update(string id, GistModel gist)69 {70 var result = await client.Gist.Edit(id, new GistUpdate71 {72 Files =73 {74 [gist.Name] = new GistFileUpdate75 {76 Content = gist.Content77 }78 },79 Description = gist.Description80 });81 return result?.Id;82 }83 public async Task<GistModel?> Find(string id)84 {85 var result = await client.Gist.Get(id);86 if (result != null)87 {88 var firstEntry = result.Files.FirstOrDefault();89 return new GistModel(firstEntry.Value.Filename, firstEntry.Value.Content)90 {91 };92 }93 return null;94 }95 private async Task<Credentials> FetchGitCredential(Uri redirectPage)96 {97 var targetUrl = await GetRedirectCallbackResult(redirectPage);98 var queryString = QueryStringHelper.ToDictionary(targetUrl);99 var code = queryString[gitHubModel.TargetRedirectKey!];100 var result = await client.Oauth.CreateAccessToken(101 new OauthTokenRequest(gitHubModel.ClientId, gitHubModel.ClientSecret, code));102 return new Credentials(result.AccessToken);103 }104 private async Task<Uri> GetRedirectCallbackResult(Uri redirectPage)105 {106 var revisionInfo = await browserFetcher107 .DownloadAsync(PuppeteerSharp.BrowserFetcher.DefaultRevision);108 using var browser = await PuppeteerSharp.Puppeteer.LaunchAsync(new PuppeteerSharp.LaunchOptions109 {110 Headless = false,111 LogProcess = true,112 DumpIO = true113 });114 var page = await browser.NewPageAsync();115 var redirectResult = await page.GoToAsync(redirectPage.AbsoluteUri);116 var target = await browser.WaitForTargetAsync(e => e.Url.Contains(gitHubModel.RedirectUrl!));117 return new Uri(target.Url);118 }119 }120}...

Full Screen

Full Screen

Program.cs

Source:Program.cs Github

copy

Full Screen

...3namespace web_browser_csharp4{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

1using PuppeteerSharp;2using System;3namespace HlidacStatu.Util.WebShot4{5 public class PuppeteerBrowser : IDisposable6 {7 static PuppeteerBrowser()8 {9 new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision).Wait();10 }11 public static Devmasters.Core.Logging.Logger logger = new Devmasters.Core.Logging.Logger("HlidacStatu.Util.Webshots");12 private static readonly PuppeteerBrowser theOnlyInstance = new PuppeteerBrowser("theOnlyInstance");13 public static PuppeteerBrowser TheOnlyStaticInstance14 {15 get16 {17 return theOnlyInstance;18 }19 }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();68 }69 internal void RecreatedChrome()70 {71 logger.Info($"{this.Name}: Recreating PuppeteerBrowser");72 lock (browserLock)73 {74 this.page.Dispose();75 this.browser.CloseAsync().Wait();76 }77 System.Threading.Thread.Sleep(500);78 Init();79 }80 #region IDisposable Support81 private bool disposedValue = false; // To detect redundant calls82 protected virtual void Dispose(bool disposing)83 {84 logger.Info($"{this.Name}: Disposing PuppeteerBrowser Instance");85 if (!disposedValue)86 {87 if (disposing)88 {89 // TODO: dispose managed state (managed objects).90 }91 logger.Debug($"{this.Name}: Closing PuppeteerBrowser");92 this.browser.CloseAsync().Wait();93 logger.Debug($"{this.Name}: Closed PuppeteerBrowser");94 // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.95 // TODO: set large fields to null.96 disposedValue = true;97 }98 }99 // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.100 ~PuppeteerBrowser()101 {102 // Do not change this code. Put cleanup code in Dispose(bool disposing) above.103 Dispose(false);104 }105 // This code added to correctly implement the disposable pattern.106 public void Dispose()107 {108 // Do not change this code. Put cleanup code in Dispose(bool disposing) above.109 Dispose(true);110 // TODO: uncomment the following line if the finalizer is overridden above.111 GC.SuppressFinalize(this);112 }113 #endregion114 }...

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];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}27public class PageResult {28 public PuppeteerSharp.Browser Browser {get; set; }29 public PuppeteerSharp.Page Page {get; set; }30 /*31 For deconstruct in dotnet see this: https://docs.microsoft.com/en-us/dotnet/csharp/deconstruct32 */33 public void Deconstruct(out PuppeteerSharp.Page page,34 out PuppeteerSharp.Browser browser){35 page = this.Page;36 browser = this.Browser;37 }38}...

Full Screen

Full Screen

PuppeteerDocumentGenerator.cs

Source:PuppeteerDocumentGenerator.cs Github

copy

Full Screen

1using PuppeteerSharp;2using PuppeteerSharp.Media;3using System.Threading.Tasks;4namespace PuppetPdf5{6 public class PuppeteerDocumentGenerator : DocumentGeneratorBase7 {8 public async Task<byte[]> Generate(string html)9 {10 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);11 var browser = await Puppeteer.LaunchAsync(new LaunchOptions12 {13 Headless = true,14 // If needed, we can specify a specific version of Chrome15 //ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",16 //IgnoredDefaultArgs = new string[] { "--disable-extensions" },17 //IgnoreDefaultArgs = true,18 });19 using (var page = await browser.NewPageAsync())20 {21 await page.SetContentAsync(html);22 var pdfData = await page.PdfDataAsync(new PdfOptions23 {24 MarginOptions = new MarginOptions25 {...

Full Screen

Full Screen

Puppeteer

Using AI Code Generation

copy

Full Screen

1using PuppeteerSharp;2using System;3using System.Threading.Tasks;4{5 {6 static async Task Main(string[] args)7 {8 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);9 var browser = await Puppeteer.LaunchAsync(new LaunchOptions10 {11 ExecutablePath = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"12 });13 var page = await browser.NewPageAsync();14 await page.ScreenshotAsync("C:\\Users\\Public\\Documents\\PuppeteerSharp\\screenshot.png");15 await browser.CloseAsync();16 Console.WriteLine("Done");17 Console.ReadLine();18 }19 }20}21using PuppeteerSharp;22using System;23using System.Threading.Tasks;24{25 {26 static async Task Main(string[] args)27 {28 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);29 var browser = await Puppeteer.LaunchAsync(new LaunchOptions30 {31 ExecutablePath = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"32 });33 var page = await browser.NewPageAsync();34 await page.ScreenshotAsync("C:\\Users\\Public\\Documents\\PuppeteerSharp\\screenshot.png");35 await browser.CloseAsync();36 Console.WriteLine("Done");37 Console.ReadLine();38 }39 }40}

Full Screen

Full Screen

Puppeteer

Using AI Code Generation

copy

Full Screen

1using PuppeteerSharp;2using System;3using System.Threading.Tasks;4{5 {6 static async Task Main(string[] args)7 {8 {9 Args = new string[] { "--no-sandbox", "--disable-setuid-sandbox" }10 };11 using (var browser = await Puppeteer.LaunchAsync(options))12 {13 using (var page = await browser.NewPageAsync())14 {15 await page.ScreenshotAsync("google.png");16 }17 }18 }19 }20}21 <RunCommandArguments>run --rm --volume ${workspaceFolder}:/app/ --workdir /app/ mcr.microsoft.com/dotnet/core/sdk:2.1 dotnet run</RunCommandArguments>22 <RunCommandArguments>run --rm --volume ${workspaceFolder}:/app/ --workdir /app/ mcr.microsoft.com/dotnet/core/sdk:2.1 dotnet run</RunCommandArguments>23{24 {25 "name": ".NET Core Launch (console)",

Full Screen

Full Screen

Puppeteer

Using AI Code Generation

copy

Full Screen

1using PuppeteerSharp;2using System;3using System.IO;4using System.Threading.Tasks;5{6 {7 static void Main(string[] args)8 {9 Console.WriteLine("Hello World!");10 CapturePage().Wait();11 }12 private static async Task CapturePage()13 {14 {15 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",16 };17 using (var browser = await Puppeteer.LaunchAsync(options))18 {19 var page = await browser.NewPageAsync();20 await page.ScreenshotAsync("google.png");21 }22 }23 }24}

Full Screen

Full Screen

Puppeteer

Using AI Code Generation

copy

Full Screen

1{2 {3 static void Main(string[] args)4 {5 Console.WriteLine("Hello World!");6 }7 }8}9{10 {11 static void Main(string[] args)12 {13 Console.WriteLine("Hello World!");14 }15 }16}17{18 {19 static void Main(string[] args)20 {21 Console.WriteLine("Hello World!");22 }23 }24}25{26 {27 static void Main(string[] args)28 {29 Console.WriteLine("Hello World!");30 }31 }32}33{34 {35 static void Main(string[] args)36 {37 Console.WriteLine("Hello World!");38 }39 }40}41{42 {43 static void Main(string[] args)44 {45 Console.WriteLine("Hello World!");46 }47 }48}49{50 {51 static void Main(string[] args)52 {53 Console.WriteLine("Hello World!");54 }55 }56}57{58 {59 static void Main(string[] args)60 {61 Console.WriteLine("Hello World!");62 }63 }64}65{66 {67 static void Main(string[] args)68 {69 Console.WriteLine("Hello World!");70 }71 }72}73{74 {

Full Screen

Full Screen

Puppeteer

Using AI Code Generation

copy

Full Screen

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 });11 var page = await browser.NewPageAsync();12 await page.WaitForSelectorAsync("input[name='q']");13 await page.TypeAsync("input[name='q']", "PuppeteerSharp");14 await page.Keyboard.PressAsync("Enter");15 await page.WaitForSelectorAsync("div.g");16 var result = await page.EvaluateExpressionAsync<string>("document.querySelector('div.g').innerText");17 Console.WriteLine(result);18 Console.ReadLine();19 await browser.CloseAsync();20 }21 }22}23Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "2", "2.csproj", "{A1E0A9A9-6A5D-4A23-9E2E-2A5D5A8B0B5E}"24 GlobalSection(SolutionConfigurationPlatforms) = preSolution

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