Best Puppeteer-sharp code snippet using PuppeteerSharp.BrowserFetcher.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 {...
PuppeteerConnection.cs
Source:PuppeteerConnection.cs
...4 public class PuppeteerConnection5 {6 public async Task<T> PuppeteerGrabber<T>(string? url, string? infoCode, string? waitSelector)7 {8 BrowserFetcher browserFetcher = new BrowserFetcher();9 await browserFetcher.DownloadAsync(BrowserFetcher.DefaultChromiumRevision);10 using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions11 {12 Headless = false,13 IgnoreHTTPSErrors = true,14 /*15 Args = new[]16 {17 "--proxy-server=http://ehmseto_01:YouMeK100@smoproxy:8080/",18 "--no-sandbox",19 "--disable-infobars",20 "--disable-setuid-sandbox",21 "--ignore-certificate-errors",22 }23 */...
BrowserFetcher
Using AI Code Generation
1var fetcher = new BrowserFetcher();2await fetcher.DownloadAsync(BrowserFetcher.DefaultRevision);3var browser = await Puppeteer.LaunchAsync(new LaunchOptions4{5 ExecutablePath = fetcher.GetExecutablePath(BrowserFetcher.DefaultRevision)6});7var fetcher = new BrowserFetcher();8var revisionInfo = await fetcher.DownloadAsync(BrowserFetcher.DefaultRevision);9var browser = await Puppeteer.LaunchAsync(new LaunchOptions10{11});12var fetcher = new BrowserFetcher();13var revisionInfo = await fetcher.DownloadAsync(BrowserFetcher.DefaultRevision);14var browser = await Puppeteer.LaunchAsync(new LaunchOptions15{16 ExecutablePath = fetcher.GetExecutablePath(BrowserFetcher.DefaultRevision)17});18var fetcher = new BrowserFetcher();19var revisionInfo = await fetcher.DownloadAsync(BrowserFetcher.DefaultRevision);20var browser = await Puppeteer.LaunchAsync(new LaunchOptions21{22});23var fetcher = new BrowserFetcher();24var revisionInfo = await fetcher.DownloadAsync(BrowserFetcher.DefaultRevision);25var browser = await Puppeteer.LaunchAsync(new LaunchOptions26{27});28var fetcher = new BrowserFetcher();29var revisionInfo = await fetcher.DownloadAsync(BrowserFetcher.DefaultRevision);30var browser = await Puppeteer.LaunchAsync(new LaunchOptions31{32});33var fetcher = new BrowserFetcher();34var revisionInfo = await fetcher.DownloadAsync(BrowserFetcher.DefaultRevision);
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(BrowserFetcher.DefaultRevision);10 Console.WriteLine(revisionInfo.ExecutablePath);11 }12 }13}
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(BrowserFetcher.DefaultRevision);10 Console.WriteLine(revisionInfo.ExecutablePath);11 Console.ReadLine();12 }13 }14}
BrowserFetcher
Using AI Code Generation
1using PuppeteerSharp;2using System;3using System.Threading.Tasks;4{5 {6 static async Task Main(string[] args)7 {8 var browserFetcher = new BrowserFetcher();9 var revisionInfo = await browserFetcher.DownloadAsync(BrowserFetcher.DefaultRevision);10 Console.WriteLine(revisionInfo.ExecutablePath);11 Console.ReadLine();12 }13 }14}15public async Task<RevisionInfo> DownloadAsync(string revision)16using PuppeteerSharp;17using System;18using System.Threading.Tasks;19{20 {21 static async Task Main(string[] args)22 {23 var browserFetcher = new BrowserFetcher();24 var revisionInfo = browserFetcher.GetRevisionInfo(BrowserFetcher.DefaultRevision);25 Console.WriteLine(revisionInfo.ExecutablePath);26 Console.ReadLine();27 }28 }29}30public RevisionInfo GetRevisionInfo(string revision)
BrowserFetcher
Using AI Code Generation
1using PuppeteerSharp;2{3 {4 static void Main(string[] args)5 {6 var browserFetcher = new BrowserFetcher();7 var revisionInfo = browserFetcher.DownloadAsync("533271");8 System.Console.WriteLine(revisionInfo.Result.LocalPath);9 }10 }11}
BrowserFetcher
Using AI Code Generation
1using PuppeteerSharp;2using System;3using System.IO;4using System.Threading.Tasks;5{6 {7 static void Main(string[] args)8 {9 MainAsync().GetAwaiter().GetResult();10 }11 static async Task MainAsync()12 {13 var browserFetcher = new BrowserFetcher();14 var revisionInfo = await browserFetcher.DownloadAsync(BrowserFetcher.DefaultRevision);15 var browser = await Puppeteer.LaunchAsync(new LaunchOptions16 {17 });18 var page = await browser.NewPageAsync();19 await page.ScreenshotAsync("google.png");20 await browser.CloseAsync();21 }22 }23}24using PuppeteerSharp;25using System;26using System.IO;27using System.Threading.Tasks;28{29 {30 static void Main(string[] args)31 {32 MainAsync().GetAwaiter().GetResult();33 }34 static async Task MainAsync()35 {36 var browserFetcher = new BrowserFetcher();37 var revisionInfo = await browserFetcher.DownloadAsync(BrowserFetcher.DefaultRevision);38 var browser = await Puppeteer.LaunchAsync(new LaunchOptions39 {40 });41 var page = await browser.NewPageAsync();42 await page.ScreenshotAsync("google.png");43 await browser.CloseAsync();44 }45 }46}47using PuppeteerSharp;48using System;49using System.IO;50using System.Threading.Tasks;51{52 {53 static void Main(string[] args)54 {55 MainAsync().GetAwaiter().GetResult();56 }
BrowserFetcher
Using AI Code Generation
1var browserFetcher = new BrowserFetcher();2var revisionInfo = await browserFetcher.DownloadAsync(RevisionInfo.ChromeRevision);3var browser = await Puppeteer.LaunchAsync(new LaunchOptions4{5});6var page = await browser.NewPageAsync();7var title = await page.GetTitleAsync();8Console.WriteLine(title);9await browser.CloseAsync();
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!!