How to use Browser class of PuppeteerSharp package

Best Puppeteer-sharp code snippet using PuppeteerSharp.Browser

Methods.cs

Source:Methods.cs Github

copy

Full Screen

...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);...

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}"); ...

Full Screen

Full Screen

ApiFactory.cs

Source:ApiFactory.cs Github

copy

Full Screen

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

Crawler.cs

Source:Crawler.cs Github

copy

Full Screen

...18 private string url;19 private double searchRadius;20 private string browserPath;21 private Dictionary<string, string> browserArgs = new Dictionary<string, string>();22 private PuppeteerSharp.Browser browser;23 private PuppeteerSharp.Page page;24 private bool isFirstPage = true;25 public Crawler SetPhrase(string phrase)26 {27 this.phrase = phrase.Replace(" ", "+");28 this.url = $"{_GoogleMapUrl}/{this.phrase}";29 return this;30 }31 public double SearchRadius { set => this.searchRadius = value; get => searchRadius; }32 public string BrowserPath { set => this.browserPath = value; get => browserPath; }33 private double sourceLat;34 private double sourceLon;35 private HtmlDocument doc = new HtmlDocument();36 public Crawler SetProxy(string host, int port)37 {38 if (browserArgs.ContainsKey("proxy"))39 {40 browserArgs["proxy"] = string.Concat("--proxy-server=", host, ":", port);41 }42 else43 {44 browserArgs.Add("proxy", string.Concat("--proxy-server=", host, ":", port));45 }46 return this;...

Full Screen

Full Screen

DocumentsV2Controller.cs

Source:DocumentsV2Controller.cs Github

copy

Full Screen

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

Full Screen

Full Screen

PuppeteerUtility.csx

Source:PuppeteerUtility.csx Github

copy

Full Screen

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

Browser

Using AI Code Generation

copy

Full Screen

1using PuppeteerSharp;2using System;3using System.Threading.Tasks;4{5 static async Task Main(string[] args)6 {7 var browser = await Puppeteer.LaunchAsync(new LaunchOptions8 {9 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"10 });11 var page = await browser.NewPageAsync();12 await page.ScreenshotAsync("google.png");13 await browser.CloseAsync();14 }15}

Full Screen

Full Screen

Browser

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 browserFetcher = new BrowserFetcher();9 await browserFetcher.DownloadAsync(BrowserFetcher.DefaultRevision);10 var browser = await Puppeteer.LaunchAsync(new LaunchOptions11 {12 Args = new[] { "--no-sandbox" }13 });14 var page = await browser.NewPageAsync();15 await page.ScreenshotAsync("google.png");16 await browser.CloseAsync();17 }18 }19}20using PuppeteerSharp;21using System;22using System.Threading.Tasks;23{24 {25 static async Task Main(string[] args)26 {27 var browserFetcher = new BrowserFetcher();28 await browserFetcher.DownloadAsync(BrowserFetcher.DefaultRevision);29 var browser = await Puppeteer.LaunchAsync(new LaunchOptions30 {31 Args = new[] { "--no-sandbox" }32 });33 var page = await browser.NewPageAsync();34 await page.ScreenshotAsync("google.png");35 await browser.CloseAsync();36 }37 }38}39using PuppeteerSharp;40using System;41using System.Threading.Tasks;42{43 {44 static async Task Main(string[] args)45 {46 var browserFetcher = new BrowserFetcher();47 await browserFetcher.DownloadAsync(BrowserFetcher.DefaultRevision);48 var browser = await Puppeteer.LaunchAsync(new LaunchOptions49 {50 Args = new[] { "--no-sandbox" }51 });52 var page = await browser.NewPageAsync();53 await page.ScreenshotAsync("google.png");54 await browser.CloseAsync();55 }56 }57}58using PuppeteerSharp;59using System;60using System.Threading.Tasks;61{62 {63 static async Task Main(string[] args

Full Screen

Full Screen

Browser

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 using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions9 {10 }))11 using (var page = await browser.NewPageAsync())12 {13 await page.ScreenshotAsync("google.png");14 }15 }16 }17}

Full Screen

Full Screen

Browser

Using AI Code Generation

copy

Full Screen

1using PuppeteerSharp;2using System;3using System.Threading.Tasks;4{5 {6 static void Main(string[] args)7 {8 MainAsync(args).GetAwaiter().GetResult();9 }10 static async Task MainAsync(string[] args)11 {12 using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions13 {14 }))15 using (var page = await browser.NewPageAsync())16 {17 await page.ScreenshotAsync("google.png");18 }19 }20 }21}22using PuppeteerSharp;23using System;24using System.Threading.Tasks;25{26 {27 static void Main(string[] args)28 {29 MainAsync(args).GetAwaiter().GetResult();30 }31 static async Task MainAsync(string[] args)32 {33 using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions34 {35 }))36 using (var page = await browser.NewPageAsync())37 {38 await page.ScreenshotAsync("google.png");39 }40 }41 }42}

Full Screen

Full Screen

Browser

Using AI Code Generation

copy

Full Screen

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 LaunchOptions { Headless = false });13 var page = await browser.NewPageAsync();14 }15 }16}17 at PuppeteerSharp.ChromiumProcess.GetExecutablePath()18 at PuppeteerSharp.ChromiumProcess..cctor()19 at PuppeteerSharp.ChromiumProcess..ctor()20 at PuppeteerSharp.Puppeteer.LaunchAsync(LaunchOptions options)21 at PuppeteerSharp.Program.MainAsync() in C:\Users\user\source\repos\puppeteer-sharp\puppeteer-sharp\Program.cs:line 2122 at PuppeteerSharp.Program.MainAsync() in C:\Users\user\source\repos\puppeteer-sharp\puppeteer-sharp\Program.cs:line 2223 at PuppeteerSharp.Program.Main(String[] args) in C:\Users\user\source\repos\puppeteer-sharp\puppeteer-sharp\Program.cs:line 924using PuppeteerSharp;25using System;26using System.Threading.Tasks;27{28 {29 static void Main(string[] args)30 {31 MainAsync().Wait();32 }33 static async Task MainAsync()34 {

Full Screen

Full Screen

Browser

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 static async Task Main(string[] args)6 {7 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);8 using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true }))9 {10 using (var page = await browser.NewPageAsync())11 {12 await page.ScreenshotAsync("google.png");13 }14 }15 }16}17using System;18using System.Threading.Tasks;19using PuppeteerSharp;20{21 static async Task Main(string[] args)22 {23 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);24 using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true }))25 {26 using (var page = await browser.NewPageAsync())27 {28 await page.ScreenshotAsync("google.png");29 }30 }31 }32}33using System;34using System.Threading.Tasks;35using PuppeteerSharp;36{37 static async Task Main(string[] args)38 {39 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);40 using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true }))41 {42 using (var page = await browser.NewPageAsync())43 {44 await page.ScreenshotAsync("google.png");45 }46 }47 }48}49using System;50using System.Threading.Tasks;51using PuppeteerSharp;52{53 static async Task Main(string[] args)54 {55 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);56 using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true }))57 {

Full Screen

Full Screen

Browser

Using AI Code Generation

copy

Full Screen

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 var title = await page.EvaluateExpressionAsync<string>("document.title");12 System.Console.WriteLine(title);13 }14 }15}16using PuppeteerSharp;17using System.Threading.Tasks;18{19 {20 static async Task Main(string[] args)21 {22 var browser = await Puppeteer.LaunchAsync(new LaunchOptions23 {24 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"25 });26 var page = await browser.NewPageAsync();27 var title = await page.EvaluateExpressionAsync<string>("document.title");28 System.Console.WriteLine(title);29 }30 }31}32using PuppeteerSharp;33using System.Threading.Tasks;34{35 {36 static async Task Main(string[] args)37 {38 var browser = await Puppeteer.LaunchAsync(new LaunchOptions39 {40 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"41 });42 var page = await browser.NewPageAsync();43 var title = await page.EvaluateExpressionAsync<string>("document.title");44 System.Console.WriteLine(title);

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.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful