How to use Request class of PuppeteerSharp package

Best Puppeteer-sharp code snippet using PuppeteerSharp.Request

Methods.cs

Source:Methods.cs Github

copy

Full Screen

...167 private static void StopYoveProxyInternalServer(BotData data)168 => data.TryGetObject<ProxyClient>("puppeteer.yoveproxy")?.Dispose();169 private static async Task SetPageLoadingOptions(BotData data, PuppeteerSharp.Page page)170 {171 await page.SetRequestInterceptionAsync(true);172 page.Request += (sender, e) =>173 {174 // If we only want documents and scripts but the resource is not one of those, block175 if (data.ConfigSettings.BrowserSettings.LoadOnlyDocumentAndScript && 176 e.Request.ResourceType != ResourceType.Document && e.Request.ResourceType != ResourceType.Script)177 {178 e.Request.AbortAsync();179 }180 // If the url contains one of the blocked urls181 else if (data.ConfigSettings.BrowserSettings.BlockedUrls182 .Where(u => !string.IsNullOrWhiteSpace(u))183 .Any(u => e.Request.Url.Contains(u, StringComparison.OrdinalIgnoreCase)))184 {185 e.Request.AbortAsync();186 }187 // Otherwise all good, continue188 else189 {190 e.Request.ContinueAsync();191 }192 };193 if (data.ConfigSettings.BrowserSettings.DismissDialogs)194 {195 page.Dialog += (sender, e) =>196 {197 data.Logger.Log($"Dialog automatically dismissed: {e.Dialog.Message}", LogColors.DarkSalmon);198 e.Dialog.Dismiss();199 };200 }201 }202 }203}...

Full Screen

Full Screen

GeneratePdf.cs

Source:GeneratePdf.cs Github

copy

Full Screen

...19 /// <param name="req"></param>20 /// <param name="log"></param>21 /// <returns></returns>22 [FunctionName("version")]23 public IActionResult Version([HttpTrigger(AuthorizationLevel.Anonymous, "get")] HttpRequest req, ILogger log)24 {25 return new OkObjectResult(Assembly.GetExecutingAssembly().GetName().Version.ToString());26 }27 /// <summary>28 /// Create a PDF from a given URL29 /// </summary>30 /// <param name="req"></param>31 /// <param name="log"></param>32 /// <returns></returns>33 [FunctionName("GeneratePdf")]34 public async Task<IActionResult> GenerateThePdf([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log)35 {36 // we need a url at the very least37 string url = req.Query["url"];38 if (string.IsNullOrEmpty(url))39 {40 return new BadRequestObjectResult("url not given");41 }42 // make sure we have a full url43 url = url.ToWebsite();44 int width = req.Query["w"].ToString().ToInt(1024);45 int margin = req.Query["m"].ToString().ToInt(0);46 string name = req.Query["n"].ToString().Clean();47 bool printBackground = req.Query["pb"].ToString().ToBool(true);48 49 if (string.IsNullOrEmpty(name))50 name = $"{DateTime.UtcNow:yyyy-MM-dd-hh-mm-ss}.pdf";51 if (!name.EndsWith(".pdf"))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 page81 await page.EmulateMediaTypeAsync(PuppeteerSharp.Media.MediaType.Screen);82 // define some options83 var options = new PdfOptions()84 {85 Width = width,86 Height = 1080,87 Format = PuppeteerSharp.Media.PaperFormat.Letter,88 DisplayHeaderFooter = false,89 PrintBackground = printBackground90 };91 // throws an error if margin is less than 1092 if (margin >= 10)93 {94 options.MarginOptions = new PuppeteerSharp.Media.MarginOptions()95 {96 Top = $"{margin}",97 Bottom = $"{margin}",98 Left = $"{margin}",99 Right = $"{margin}"100 };101 }102 // get the bytes of the pdf103 var pdfData = await page.PdfDataAsync(options);104 // write out the pdf105 return new FileContentResult(pdfData, "application/pdf")106 {107 FileDownloadName = name108 };109 }110 catch(Exception ex)111 {112 return new BadRequestObjectResult(ex.Message);113 } 114 }115 }116}...

Full Screen

Full Screen

GistGithubService.cs

Source:GistGithubService.cs Github

copy

Full Screen

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

Full Screen

Full Screen

AccountsControllerIntegrationTests.cs

Source:AccountsControllerIntegrationTests.cs Github

copy

Full Screen

...13{14 [Collection("WebHost collection")]15 public class AccountsControllerIntegrationTests : IClassFixture<AuthServerWebApplicationFactory<TestStartup, AppIdentityDbContext>>16 {17 private static readonly IList<SignupRequest> _signupRequests = new List<SignupRequest>18 {19 new SignupRequest() {FullName = "Mark Macneil", Email = "mark@fullstackmark.com", Password="Pa$$w0rd!", Role="applicant"},20 new SignupRequest() {FullName = "Prescott Terrell", Email = "pterrell@mailinator.com", Password="Pa$$w0rd!", Role="employer"}21 };22 private readonly HttpClient _client;23 private readonly WebHostFixture _webHostFixture;24 public AccountsControllerIntegrationTests(AuthServerWebApplicationFactory<TestStartup, AppIdentityDbContext> factory, WebHostFixture webHostFixture)25 {26 _client = factory.CreateClient();27 _webHostFixture = webHostFixture;28 }29 [Fact]30 public async Task CanCreateAccount()31 {32 var httpResponse = await _client.SendAsync(new HttpRequestMessage(HttpMethod.Post, "/api/accounts")33 {34 Content = new StringContent(System.Text.Json.JsonSerializer.Serialize(_signupRequests[0]), Encoding.UTF8, "application/json")35 });36 httpResponse.EnsureSuccessStatusCode();37 // Deserialize and examine results.38 var stringResponse = await httpResponse.Content.ReadAsStringAsync();39 var response = JsonConvert.DeserializeObject<SignupResponse>(stringResponse);40 Assert.Equal(_signupRequests[0].FullName, response.FullName);41 Assert.Equal(_signupRequests[0].Email, response.Email);42 Assert.Equal(_signupRequests[0].Role, response.Role);43 Assert.True(Guid.TryParse(response.Id, out _));44 }45 [Fact]46 public async Task CanLogin()47 {48 // 1. Create a new account against the InMemory database49 var httpResponse = await _client.SendAsync(new HttpRequestMessage(HttpMethod.Post, "/api/accounts")50 {51 Content = new StringContent(System.Text.Json.JsonSerializer.Serialize(_signupRequests[1]), Encoding.UTF8, "application/json")52 });53 httpResponse.EnsureSuccessStatusCode();54 // 2. Ensure PuppeteerSharp has the browser downloaded55 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);56 using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true }))57 {58 using (var page = await browser.NewPageAsync())59 {60 // 3. Navigate to the test client page61 await page.GoToAsync($"http://{_webHostFixture.Host}/test-client/index.html");62 var navigationTask = page.WaitForNavigationAsync();63 await Task.WhenAll(navigationTask, page.ClickAsync("button"));64 // 4. Fill out the login form65 await page.TypeAsync("#Username", _signupRequests[1].Email);66 await page.TypeAsync("#Password", _signupRequests[1].Password);67 // 5. Hit the login button and wait for redirect navigation...68 navigationTask = page.WaitForNavigationAsync(new NavigationOptions { WaitUntil = new[] { WaitUntilNavigation.Networkidle0 } });69 await Task.WhenAll(navigationTask, page.ClickAsync(".btn-primary"));70 var content = await page.GetContentAsync();71 await page.CloseAsync();72 // 6. Assert we have a logged-in state in the test client73 Assert.Contains("User logged in", content);74 Assert.Contains("Prescott Terrell", content);75 Assert.Contains("pterrell@mailinator.com", content);76 Assert.Contains("employer", content);77 }78 }79 }80 }...

Full Screen

Full Screen

AvitoPostParser.cs

Source:AvitoPostParser.cs Github

copy

Full Screen

...17 {18 var response =await page.GoToAsync(url);19 if (response.Status == HttpStatusCode.Forbidden)20 {21 throw new HttpRequestException("Forbidden");22 }23 if (response.Url.Contains("/blocked"))24 {25 ///todo try recognize captcha26 throw new HttpRequestException("Blocked");27 }28 var getPhoneNumberButton = await page.QuerySelectorAsync("span.item-phone-button-sub-text");29 if (getPhoneNumberButton == null)30 {31 return null;32 }33 await getPhoneNumberButton.ClickAsync();34 string phoneNumber = await GetPhoneNumber(page);35 string authorName = await GetAuthorName(page);36 return new PostInformation37 {38 Author = new Author39 {40 PhoneNumber = phoneNumber,...

Full Screen

Full Screen

PuppeteerEngine.cs

Source:PuppeteerEngine.cs Github

copy

Full Screen

...28 dic.Add("Accept-Encoding", "gzip, deflate, br");29 dic.Add("Accept-Language", "zh-TW,zh;q=0.9,en-US;q=0.8,en;q=0.7,zh-CN;q=0.6");30 dic.Add("Connection", "keep-alive");31 await page.EmulateAsync(IPhone);32 await page.SetRequestInterceptionAsync(true);33 await page.SetExtraHttpHeadersAsync(dic);34 page.Request += async (sender, e) =>35 {36 if (e.Request.ResourceType == ResourceType.Image)37 await e.Request.AbortAsync();38 else39 await e.Request.ContinueAsync();40 };41 return page;42 }43 public async void launchBrowser(){44 _browser = await Puppeteer.LaunchAsync(new LaunchOptions45 {46 ExecutablePath = _settings.ChromePath,47 Headless = false48 });49 }50 }51}...

Full Screen

Full Screen

Html2PdfApiService.cs

Source:Html2PdfApiService.cs Github

copy

Full Screen

...34 DisplayHeaderFooter = true,35 PrintBackground = true,36 };37 }38 public override async Task CreatePdf(CreatePdfRequest request, IServerStreamWriter<CreatePdfReply> responseStream, ServerCallContext context)39 {40 _logger.LogDebug("Generating PDF");41 await using var browser = await Puppeteer.LaunchAsync(_options);42 await using var page = await browser.NewPageAsync();43 await page.SetContentAsync(request.Html);44 await using var pdfStream = await page.PdfStreamAsync(_pdfOptions);45 46 await responseStream.WriteAsync(new CreatePdfReply47 {48 Pdf = await ByteString.FromStreamAsync(pdfStream) 49 });50 _logger.LogDebug("Export completed");51 }52 }...

Full Screen

Full Screen

PdfRequest.cs

Source:PdfRequest.cs Github

copy

Full Screen

2using PuppeteerSharp;3using PuppeteerSharp.Media;4namespace AbdusCo.Matbaa.Abstractions5{6 public class PdfRequest7 {8 public static readonly PdfOptions DefaultPdfOptions = new PdfOptions()9 {10 Format = PaperFormat.A4,11 DisplayHeaderFooter = false,12 PrintBackground = true,13 PreferCSSPageSize = true,14 };15 /// <summary>16 /// HTML to create PDF from17 /// </summary>18 public string Html { get; set; }19 public PageOptions? Options { get; set; }20 /// <summary>...

Full Screen

Full Screen

Request

Using AI Code Generation

copy

Full Screen

1using System;2using System.Collections.Generic;3using System.Linq;4using System.Threading.Tasks;5using PuppeteerSharp;6{7 {8 public static async Task Main(string[] args)9 {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}19using System;20using System.Collections.Generic;21using System.Linq;22using System.Threading.Tasks;23using PuppeteerSharp;24{25 {26 public static async Task Main(string[] args)27 {28 var browser = await Puppeteer.LaunchAsync(new LaunchOptions29 {30 });31 var page = await browser.NewPageAsync();32 await page.ScreenshotAsync("google.png");33 await browser.CloseAsync();34 }35 }36}37using System;38using System.Collections.Generic;39using System.Linq;40using System.Threading.Tasks;41using PuppeteerSharp;42{43 {44 public static async Task Main(string[] args)45 {46 var browserFetcher = new BrowserFetcher();47 await browserFetcher.DownloadAsync(BrowserFetcher.DefaultRevision);48 }49 }50}51using System;52using System.Collections.Generic;53using System.Linq;54using System.Threading.Tasks;55using PuppeteerSharp;56{57 {58 public static async Task Main(string[] args)59 {60 var browserFetcher = new BrowserFetcher();61 await browserFetcher.DownloadAsync(BrowserFetcher.DefaultRevision);62 }63 }64}65using System;66using System.Collections.Generic;67using System.Linq;68using System.Threading.Tasks;69using PuppeteerSharp;70{71 {

Full Screen

Full Screen

Request

Using AI Code Generation

copy

Full Screen

1var browser = await Puppeteer.LaunchAsync(new LaunchOptions2{3});4var page = await browser.NewPageAsync();5await page.GoToAsync(url);6var content = await page.GetContentAsync();7Console.WriteLine(content);8Console.ReadKey();9var browser = await Puppeteer.LaunchAsync(new LaunchOptions10{11});12var page = await browser.NewPageAsync();13await page.GoToAsync(url);14var content = await page.GetContentAsync();15Console.WriteLine(content);16Console.ReadKey();17var browser = await Puppeteer.LaunchAsync(new LaunchOptions18{19});20var page = await browser.NewPageAsync();21await page.GoToAsync(url);22var content = await page.GetContentAsync();23Console.WriteLine(content);24Console.ReadKey();25var browser = await Puppeteer.LaunchAsync(new LaunchOptions26{27});28var page = await browser.NewPageAsync();29await page.GoToAsync(url);30var content = await page.GetContentAsync();31Console.WriteLine(content);32Console.ReadKey();33var browser = await Puppeteer.LaunchAsync(new LaunchOptions34{35});36var page = await browser.NewPageAsync();37await page.GoToAsync(url);38var content = await page.GetContentAsync();39Console.WriteLine(content);40Console.ReadKey();41var browser = await Puppeteer.LaunchAsync(new LaunchOptions42{43});44var page = await browser.NewPageAsync();45await page.GoToAsync(url);46var content = await page.GetContentAsync();47Console.WriteLine(content);48Console.ReadKey();

Full Screen

Full Screen

Request

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 Console.WriteLine("Hello World!");9 }10 static async Task Run()11 {12 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);13 var browser = await Puppeteer.LaunchAsync(new LaunchOptions14 {15 });16 var page = await browser.NewPageAsync();17 await page.ScreenshotAsync("google.png");18 await browser.CloseAsync();19 }20 }21}22using PuppeteerSharp;23using System;24using System.Threading.Tasks;25{26 {27 static void Main(string[] args)28 {29 Console.WriteLine("Hello World!");30 }31 static async Task Run()32 {33 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);34 var browser = await Puppeteer.LaunchAsync(new LaunchOptions35 {36 });37 var page = await browser.NewPageAsync();38 await page.ScreenshotAsync("google.png");39 await browser.CloseAsync();40 }41 }42}43using PuppeteerSharp;44using System;45using System.Threading.Tasks;46{47 {48 static void Main(string[] args)49 {50 Console.WriteLine("Hello World!");51 }52 static async Task Run()53 {54 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);55 var browser = await Puppeteer.LaunchAsync(new LaunchOptions56 {57 });58 var page = await browser.NewPageAsync();59 await page.ScreenshotAsync("google.png");60 await browser.CloseAsync();61 }62 }63}64using PuppeteerSharp;65using System;

Full Screen

Full Screen

Request

Using AI Code Generation

copy

Full Screen

1using System;2using System.IO;3using System.Linq;4using System.Threading.Tasks;5using PuppeteerSharp;6using System.Collections.Generic;7{8 {9 static void Main(string[] args)10 {11 MainAsync().Wait();12 }13 static async Task MainAsync()14 {15 var browser = await Puppeteer.LaunchAsync(new LaunchOptions16 {17 Args = new List<string> { "--disable-extensions" }18 });19 var page = await browser.NewPageAsync();20 var requests = response.Request;21 var request = requests;22 var request1 = request.Url;23 Console.WriteLine(request1);24 Console.ReadLine();25 await browser.CloseAsync();26 }27 }28}29var requests = response.Request;30 var request = requests;31 var request1 = request.Url;32 Console.WriteLine(request1);33 Console.ReadLine();34var requests = response.Request;35 var request = requests;36 var request1 = request.Url;37 Console.WriteLine(request1);38 Console.ReadLine();39var requests = response.Request;40 var request = requests;41 var request1 = request.Url;42 Console.WriteLine(request1);43 Console.ReadLine();44var requests = response.Request;45 var request = requests;

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