Best Puppeteer-sharp code snippet using PuppeteerSharp.BrowserFetcher.RevisionInfo
BrowserUtils.cs
Source:BrowserUtils.cs
...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 };...
GeneratePdf.cs
Source:GeneratePdf.cs
...62 await browserFetcher.DownloadAsync();63 // launch the browser in headless mode from the temp dir we downloaded the image to64 await using var browser = await Puppeteer.LaunchAsync(new LaunchOptions { 65 Headless = true,66 ExecutablePath = browserFetcher.RevisionInfo(BrowserFetcher.DefaultChromiumRevision).ExecutablePath67 });68 // create a new page69 await using var page = await browser.NewPageAsync();70 await page.GoToAsync(url, WaitUntilNavigation.Networkidle0); // In case of fonts being loaded from a CDN, use WaitUntilNavigation.Networkidle0 as a second param.71 // change the viewport to the width of your choosing72 await page.SetViewportAsync(new ViewPortOptions73 {74 DeviceScaleFactor = 1,75 Width = width,76 Height = 108077 });78 // dimensions = await page.EvaluateExpressionAsync<string>(jsWidth);79 await page.EvaluateExpressionHandleAsync("document.fonts.ready"); // Wait for fonts to be loaded. Omitting this might result in no text rendered in pdf.80 // use the screen mode for viewing the web page...
GistGithubService.cs
Source:GistGithubService.cs
1using Octokit;2using Patrick.Helpers;3using Patrick.Models;4using System;5using System.Linq;6using System.Threading.Tasks;7namespace Patrick.Services.Implementation8{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}...
Program.cs
Source:Program.cs
...77 {78 Headless = false,79 UserDataDir = UserDataDirPath("default"),80 DefaultViewport = null,81 ExecutablePath = browserFetcher.RevisionInfo(browserRevision).ExecutablePath,82 });83 browserPage = (await browser.PagesAsync()).FirstOrDefault() ?? await browser.NewPageAsync();84 await browserPage.ExposeFunctionAsync("____callback____", (string returnValue) =>85 {86 callbackFromBrowserDelegate?.Invoke(returnValue);87 return 0;88 });89 }90}...
BrowserFetcherTests.cs
Source:BrowserFetcherTests.cs
...26 Platform = Platform.Linux,27 Path = _downloadsFolder,28 Host = TestConstants.ServerUrl29 });30 var revisionInfo = browserFetcher.RevisionInfo(123456);31 Server.SetRedirect(revisionInfo.Url.Substring(TestConstants.ServerUrl.Length), "/chromium-linux.zip");32 Assert.False(revisionInfo.Local);33 Assert.Equal(Platform.Linux, revisionInfo.Platform);34 Assert.False(await browserFetcher.CanDownloadAsync(100000));35 Assert.True(await browserFetcher.CanDownloadAsync(123456));36 try37 {38 revisionInfo = await browserFetcher.DownloadAsync(123456);39 Assert.True(revisionInfo.Local);40 Assert.Equal("LINUX BINARY\n", File.ReadAllText(revisionInfo.ExecutablePath));41 if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))42 {43#if NETCOREAPP //This will not be run on net4x anyway.44 Mono.Unix.FileAccessPermissions permissions = ConvertPermissions(LinuxSysCall.ExecutableFilePermissions);...
LoteriaCaixaService.cs
Source:LoteriaCaixaService.cs
1using System;2using System.Collections.Generic;3using System.Text;4using System.Threading.Tasks;5using Microsoft.Extensions.Configuration;6using PuppeteerSharp.Core.LoteriaCaixa.Models;7namespace PuppeteerSharp.Core.Service.LoteriaCaixa8{9 public sealed class LoteriaCaixaService : ILoteriaCaixaService10 {11 private const string _pageLoteriaCaixaUrl = "urlApiLoteriaCaixa";12 private readonly IConfiguration _configuration;13 public LoteriaCaixaService(14 IConfiguration configuration)15 => _configuration = configuration;16 public async Task<IEnumerable<Sorteio>> GetLastDrawByCrawling(17 string date = null,18 string contest = null)19 {20 IEnumerable<Sorteio> result = null;21 try22 {23 var browserFetcher = Puppeteer.CreateBrowserFetcher(new BrowserFetcherOptions());24 var revisionInfo = await browserFetcher.DownloadAsync(BrowserFetcher.DefaultRevision);25 var optionsLaunch = new LaunchOptions26 {27 Headless = true,28 ExecutablePath = revisionInfo.ExecutablePath29 };30 using (var browser = await Puppeteer.LaunchAsync(optionsLaunch))31 using (var page = await browser.NewPageAsync())32 {33 var pageUrl = _configuration.GetSection(_pageLoteriaCaixaUrl).Value;34 await page.GoToAsync(pageUrl);35 var jsSelectAllAnchors = @"() => {36 const table = document.querySelector('table');37 let items = [];38 const headers = {39 0: 'concurso',40 1:'dataSorteio',41 2:'premio1',42 3:'premio2',43 4:'premio3',44 5:'premio4',45 6:'premio5',46 7:'valPremio1',47 8:'valPremio2',48 9:'valPremio3',49 10:'valPremio4',50 11:'valPremio5'51 }52 if (table) {53 Array.from(table.rows).forEach((tr, row_ind) => {54 if(row_ind !== 0) {55 let obj = {};56 Array.from(tr.cells).forEach((cell, col_ind) => {57 obj[headers[col_ind]] = cell.textContent;58 });59 items.push(obj);60 }61 });62 }63 return items;64 }";65 var items = await page.EvaluateFunctionAsync<Sorteio[]>(jsSelectAllAnchors);66 result = items;67 await page.CloseAsync();68 }69 }70 catch (Exception ex)71 {72 }73 return result;74 }75 }76}...
General.cs
Source:General.cs
...12 // Downloads Chromium into local directory13 public static string initialize()14 {15 Console.WriteLine(string.Format(ConsoleFormatting.Indent(2) + strings.general_initialize_Download));16 RevisionInfo revision = new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision).Result;17 return string.Format(ConsoleFormatting.Indent(2) + strings.general_initialize_Complete, revision.Revision);18 }19 // Lists installed Chromium versions20 public static string installed()21 {22 var revision = new BrowserFetcher().LocalRevisions();23 string result = "";24 if (revision.Any())25 {26 int c = 0;27 foreach (int i in revision)28 {29 result += string.Format(ConsoleFormatting.Indent(2) + strings.general_installed_ChromiumVersion, i);30 c++;31 if (c < revision.Count())32 {33 result += Environment.NewLine;34 }35 }36 } 37 else38 {39 result = string.Format(ConsoleFormatting.Indent(2) + strings.general_installed_NotInstalled);40 }41 return result;42 }43 public static string install(int installrevision)44 {45 Console.WriteLine(string.Format(ConsoleFormatting.Indent(2) + strings.general_install_Download, installrevision));46 RevisionInfo revision = new BrowserFetcher().DownloadAsync(installrevision).Result;47 if (revision.Local)48 {49 return string.Format(ConsoleFormatting.Indent(2) + strings.general_install_CompleteSuccess, revision.Revision);50 }51 else52 {53 return string.Format(ConsoleFormatting.Indent(2) + strings.general_install_CompleteFailure, revision.Revision);54 }55 }56 public static string uninstall(int revision)57 {58 new BrowserFetcher().Remove(revision);59 return string.Format(ConsoleFormatting.Indent(2) + strings.general_uninstall_RemovedRevision, revision);60 }...
InstagramService.cs
Source:InstagramService.cs
1using PuppeteerSharp.Core.Instagram.Models;2using PuppeteerSharp;3using System;4using System.Collections.Generic;5using System.Linq;6using System.Text;7using System.Threading.Tasks;8namespace PuppeteerSharp.Core.Instagram.Service9{10 public sealed class InstagramService : IInstagramService11 {12 public async Task<IEnumerable<Image>> GetLastsPostsAsync(13 string profile)14 {15 IEnumerable<Image> result = null;16 try17 {18 var browserFetcher = Puppeteer.CreateBrowserFetcher(new BrowserFetcherOptions());19 var revisionInfo = await browserFetcher.DownloadAsync(BrowserFetcher.DefaultRevision);20 var optionsLaunch = new LaunchOptions21 {22 Headless = true,23 ExecutablePath = revisionInfo.ExecutablePath24 };25 using (var browser = await Puppeteer.LaunchAsync(optionsLaunch))26 using (var page = await browser.NewPageAsync())27 {28 var profileUrl = $"https://www.instagram.com/{profile}/";29 await page.GoToAsync(profileUrl);30 var jsSelectAllAnchors = @"Array.from(document.querySelectorAll('article a')).map(el => {31 const url = el.href;32 const child = el.firstChild.firstChild.firstChild33 return {34 link: url, 35 description: child.alt, 36 src: child.src37 }38 })";39 var images = await page.EvaluateExpressionAsync<Image[]>(jsSelectAllAnchors);40 result = images;41 await page.CloseAsync();42 }43 }44 catch 45 {46 }47 return result;48 }49 }50}...
RevisionInfo
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static async Task Main(string[] args)7 {8 var fetcher = new BrowserFetcher();9 var revisionInfo = await fetcher.RevisionInfo("533271");10 Console.WriteLine(revisionInfo.Revision);11 Console.WriteLine(revisionInfo.FolderPath);12 Console.WriteLine(revisionInfo.Url);13 Console.WriteLine(revisionInfo.Revision);14 }15 }16}
RevisionInfo
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static async Task Main(string[] args)7 {8 var browserFetcher = new BrowserFetcher();9 var revisionInfo = await browserFetcher.RevisionInfo("686378");10 Console.WriteLine("revisionInfo.Revision: " + revisionInfo.Revision);11 Console.WriteLine("revisionInfo.Url: " + revisionInfo.Url);12 Console.WriteLine("revisionInfo.FolderPath: " + revisionInfo.FolderPath);13 Console.WriteLine("revisionInfo.Local: " + revisionInfo.Local);14 Console.WriteLine("revisionInfo.ExecutablePath: " + revisionInfo.ExecutablePath);15 Console.WriteLine("revisionInfo.Finished: " + revisionInfo.Finished);16 Console.WriteLine("revisionInfo.DownloadedBytes: " + revisionInfo.DownloadedBytes);17 Console.WriteLine("revisionInfo.TotalBytes: " + revisionInfo.TotalBytes);18 Console.WriteLine("revisionInfo.DownloadPercent: " + revisionInfo.DownloadPercent);19 }20 }21}
RevisionInfo
Using AI Code Generation
1using PuppeteerSharp;2using System;3using System.IO;4using System.Threading.Tasks;5{6 {7 static async Task Main(string[] args)8 {9 var browserFetcher = new BrowserFetcher();10 var revisionInfo = browserFetcher.RevisionInfo("737027");11 Console.WriteLine(revisionInfo.Revision);12 Console.WriteLine(revisionInfo.FolderPath);13 Console.WriteLine(revisionInfo.Url);14 Console.WriteLine(revisionInfo.Local);15 Console.WriteLine(revisionInfo.ExecutablePath);16 Console.WriteLine(revisionInfo.Revision);17 Console.WriteLine(revisionInfo.FolderPath);18 Console.WriteLine(revisionInfo.Url);19 Console.WriteLine(revisionInfo.Local);20 Console.WriteLine(revisionInfo.ExecutablePath);21 }22 }23}24public RevisionInfo RevisionInfo(string revision)25using PuppeteerSharp;26using System;27using System.IO;28using System.Threading.Tasks;29{30 {31 static async Task Main(string[] args)
RevisionInfo
Using AI Code Generation
1using System;2using System.IO;3using System.Threading.Tasks;4using PuppeteerSharp;5{6 {7 static async Task Main(string[] args)8 {9 var browserFetcher = new BrowserFetcher();10 var revisionInfo = browserFetcher.RevisionInfo(BrowserFetcher.DefaultRevision);11 Console.WriteLine(revisionInfo.Revision);12 Console.WriteLine(revisionInfo.FolderPath);13 Console.WriteLine(revisionInfo.Url);14 Console.WriteLine(revisionInfo.Local);15 Console.WriteLine(revisionInfo.Revision);16 Console.WriteLine(revisionInfo.ExecutablePath);17 Console.WriteLine(revisionInfo.Platform);18 }19 }20}
RevisionInfo
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static async Task Main(string[] args)7 {8 if (args.Length == 0)9 {10 Console.WriteLine("Revision number is missing");11 }12 {13 var revisionInfo = await BrowserFetcher.DefaultRevisionInfoAsync(args[0]);14 Console.WriteLine(revisionInfo);15 }16 }17 }18}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!