Best Puppeteer-sharp code snippet using PuppeteerSharp.BrowserFetcher
SaveWebPage.xaml.cs
Source:SaveWebPage.xaml.cs
...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}");
...
GeneratePdf.cs
Source:GeneratePdf.cs
...52 name = $"{name}.pdf";53 try54 {55 // create a browserfetcher object which will handle the downloading of the chrome browser image56 using var browserFetcher = new BrowserFetcher(new BrowserFetcherOptions()57 {58 // for azure functions, we need to use the temp path so we don't get a permission issue59 Path = Path.GetTempPath()60 }) ;61 // download the browser image62 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...
Form1.cs
Source:Form1.cs
...18 InitializeComponent();19 }20 private async void button1_Click(object sender, EventArgs e)21 { 22 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);23 browser = await Puppeteer.LaunchAsync(new LaunchOptions24 {25 Headless = true26 });27 //å¦æawait new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);æ§è¡ä¸æå28 //å¯ä»¥æå¨è®¿é®https://commondatastorage.googleapis.com/chromium-browser-snapshots/index.html?prefix=Win_x64/ï¼ä¸è½½Chromiumæµè§å¨ï¼å¹¶è§£åå°æå®ä½ç½®29 //åéè¿ä»¥ä¸ä»£ç åå§å30 /*31 * LaunchOptions options = new LaunchOptions();32 options.Headless = true;33 options.DefaultViewport = null;34 //忽ç¥è¯ä¹¦é误35 options.IgnoreHTTPSErrors = true;36 //chromePathå°±æ¯ä¸è½½çChromiumæµè§å¨è§£åçä½ç½® 37 options.ExecutablePath = chromePath;38 browser = await Puppeteer.LaunchAsync(options);39 */40 var page = await browser.NewPageAsync();41 await page.GoToAsync(this.textBox1.Text);...
GistGithubService.cs
Source:GistGithubService.cs
...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
...66 }67 }68 static async System.Threading.Tasks.Task StartWebBrowser()69 {70 var browserRevision = PuppeteerSharp.BrowserFetcher.DefaultChromiumRevision;71 var browserFetcher = new PuppeteerSharp.BrowserFetcher(new PuppeteerSharp.BrowserFetcherOptions72 {73 Path = BrowserDownloadDirPath()74 });75 await browserFetcher.DownloadAsync(browserRevision);76 browser = await PuppeteerSharp.Puppeteer.LaunchAsync(new PuppeteerSharp.LaunchOptions77 {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 {...
PuppeteerGenerator.cs
Source:PuppeteerGenerator.cs
...85 return $"<div style=\"font-size:10px !important; color:#808080; padding-left:10px; text-align:'center'; width: 95%; \" >{string.Concat(list)}</div>";86 }87 // check if puppeteer exists locally. Download if not88 private static async Task<string> DownloadPuppeteerToPath(string path) {89 var downloadPath = path.Replace($"Win64-{BrowserFetcher.DefaultRevision}\\", "");90 var fetcherOptions = new BrowserFetcherOptions { Path = downloadPath, Platform = Platform.Win64 };91 BrowserFetcher browserFetcher = new BrowserFetcher(fetcherOptions);92 var revs = browserFetcher.LocalRevisions();93 // download if not existing in local94 if (revs == null || !revs.Any())95 await browserFetcher.DownloadAsync(BrowserFetcher.DefaultRevision);96 return browserFetcher.GetExecutablePath(BrowserFetcher.DefaultRevision);97 }98 }99}...
BrowserProvider.cs
Source:BrowserProvider.cs
...33 }34 if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("PUPPETEER_EXECUTABLE_PATH")))35 {36 logger.LogDebug("Download browser");37 using var browserFetcher = new BrowserFetcher(Options.Product);38 if (!string.IsNullOrEmpty(Options.Revision))39 {40 await browserFetcher.DownloadAsync(Options.Revision);41 }42 else43 {44 await browserFetcher.DownloadAsync();45 }46 logger.LogDebug("Browser downloaded");47 }48 logger.LogInformation("Start new Browser");49 return await PuppeteerSharp.Puppeteer.LaunchAsync(50 new LaunchOptions51 {...
PuppeteerDocumentGenerator.cs
Source:PuppeteerDocumentGenerator.cs
...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 MarginOptions...
BrowserFetcher
Using AI Code Generation
1var browserFetcher = new BrowserFetcher();2await browserFetcher.DownloadAsync(BrowserFetcher.DefaultRevision);3var browser = await Puppeteer.LaunchAsync(new LaunchOptions4{5 ExecutablePath = browserFetcher.GetExecutablePath(BrowserFetcher.DefaultRevision)6});7var page = await browser.NewPageAsync();8await page.ScreenshotAsync("google.png");9await browser.CloseAsync();10var browser = await Puppeteer.LaunchAsync(new LaunchOptions11{12});13var page = await browser.NewPageAsync();14await page.ScreenshotAsync("google.png");15await browser.CloseAsync();16var browser = await Puppeteer.LaunchAsync(new LaunchOptions17{18});19var page = await browser.NewPageAsync();20await page.ScreenshotAsync("google.png");21await browser.CloseAsync();22var browser = await Puppeteer.LaunchAsync(new LaunchOptions23{24});25var page = await browser.NewPageAsync();26await page.ScreenshotAsync("google.png");27await browser.CloseAsync();28var browser = await Puppeteer.LaunchAsync(new LaunchOptions29{30});31var page = await browser.NewPageAsync();32await page.ScreenshotAsync("google.png");33await browser.CloseAsync();34var browser = await Puppeteer.LaunchAsync(new LaunchOptions35{36});37var page = await browser.NewPageAsync();38await page.ScreenshotAsync("google.png");39await browser.CloseAsync();
BrowserFetcher
Using AI Code Generation
1var browserFetcher = new BrowserFetcher();2await browserFetcher.DownloadAsync(BrowserFetcher.DefaultRevision);3var browser = await Puppeteer.LaunchAsync(new LaunchOptions4{5 ExecutablePath = browserFetcher.GetExecutablePath(BrowserFetcher.DefaultRevision)6});7var page = await browser.NewPageAsync();8await page.ScreenshotAsync("google.png");9await browser.CloseAsync();
BrowserFetcher
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.DownloadAsync();10 var browser = await Puppeteer.LaunchAsync(new LaunchOptions11 {12 });13 var page = await browser.NewPageAsync();14 await page.ScreenshotAsync("google.png");15 await browser.CloseAsync();16 }17 }18}
BrowserFetcher
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.DownloadAsync(BrowserFetcher.DefaultRevision).Result;11 var browser = await Puppeteer.LaunchAsync(new LaunchOptions12 {13 });14 var page = await browser.NewPageAsync();15 await page.ScreenshotAsync("google.png");16 await browser.CloseAsync();17 }18 }19}
BrowserFetcher
Using AI Code Generation
1var browserFetcher = new BrowserFetcher();2await browserFetcher.DownloadAsync(BrowserFetcher.DefaultRevision);3{4};5var browser = await Puppeteer.LaunchAsync(options);6{7};8var browser = await Puppeteer.LaunchAsync(options);9var page = await browser.NewPageAsync();10await page.ScreenshotAsync("google.png");11{12};13var browser = await Puppeteer.LaunchAsync(options);14var page = await browser.NewPageAsync();15await page.ScreenshotAsync("google.png");16await browser.CloseAsync();17{18};19var browser = await Puppeteer.LaunchAsync(options);20var page = await browser.NewPageAsync();21await page.ScreenshotAsync("google.png");22await browser.CloseAsync();23{24};25var browser = await Puppeteer.LaunchAsync(options);26var page = await browser.NewPageAsync();27await page.ScreenshotAsync("google.png");28await browser.CloseAsync();
BrowserFetcher
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 = await browserFetcher.DownloadAsync(BrowserFetcher.DefaultRevision);11 var browser = await Puppeteer.LaunchAsync(new LaunchOptions12 {13 });14 var page = await browser.NewPageAsync();15 Console.ReadLine();16 await browser.CloseAsync();17 }18 }19}
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!!