How to use BrowserFetcher method of PuppeteerSharp.BrowserFetcher class

Best Puppeteer-sharp code snippet using PuppeteerSharp.BrowserFetcher.BrowserFetcher

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

GeneratePdf.cs

Source:GeneratePdf.cs Github

copy

Full Screen

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

Full Screen

Full Screen

Form1.cs

Source:Form1.cs Github

copy

Full Screen

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

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

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

Full Screen

Full Screen

PuppeteerGenerator.cs

Source:PuppeteerGenerator.cs Github

copy

Full Screen

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

Full Screen

Full Screen

BrowserProvider.cs

Source:BrowserProvider.cs Github

copy

Full Screen

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

Full Screen

Full Screen

PuppeteerConnection.cs

Source:PuppeteerConnection.cs Github

copy

Full Screen

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

Full Screen

Full Screen

BrowserFetcher

Using AI Code Generation

copy

Full Screen

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

Full Screen

Full Screen

BrowserFetcher

Using AI Code Generation

copy

Full Screen

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}

Full Screen

Full Screen

BrowserFetcher

Using AI Code Generation

copy

Full Screen

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}

Full Screen

Full Screen

BrowserFetcher

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

Full Screen

Full Screen

BrowserFetcher

Using AI Code Generation

copy

Full Screen

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}

Full Screen

Full Screen

BrowserFetcher

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

Full Screen

Full Screen

BrowserFetcher

Using AI Code Generation

copy

Full Screen

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

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