How to use SetUserAgentAsync method of PuppeteerSharp.Page class

Best Puppeteer-sharp code snippet using PuppeteerSharp.Page.SetUserAgentAsync

WebScraper.cs

Source:WebScraper.cs Github

copy

Full Screen

...52 {53 Console.WriteLine("Error:" + e.ToString());54 };55 m_page.Console += (s, e) => { Console.WriteLine(e.Message.Text); };56 m_page.SetUserAgentAsync(agent).Wait();57 }58 /// <summary>59 /// Set username and password to authenticate against web pages with.60 /// </summary>61 /// <param name="username">Username to authenticate with</param>62 /// <param name="password">Password to autrhenticate with.</param>63 public void SetAuth(string username, string password)64 {65 SetAuthAsync(username, password).Wait();66 }67 private async Task SetAuthAsync(string username, string password)68 {69 await m_page.AuthenticateAsync(new Credentials {Username = username, Password = password});70 }...

Full Screen

Full Screen

BrowserUtils.cs

Source:BrowserUtils.cs Github

copy

Full Screen

...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 };163 string originalUserAgent = await browser.GetUserAgentAsync();164 await page.SetUserAgentAsync($"{originalUserAgent} {USER_AGENT_SUFFIX}");165 if (cookies.Any()) {166 await page.SetCookieAsync(cookies.ToArray());167 }168 await page.GoToAsync(url, navigationOptions);169 return await page.ScreenshotDataAsync(options);170 } finally {171 await Cleanup(page);172 }173 } finally {174 Cleanup(browser);175 }176 }177 public bool UserAgentMatches(string userAgent) {178 return userAgent.EndsWith($" {USER_AGENT_SUFFIX}");...

Full Screen

Full Screen

FacebookBrowser.cs

Source:FacebookBrowser.cs Github

copy

Full Screen

...61 public async Task Login()62 {63 var browser = await GetLaunchedBrowser();64 var page = (await browser.PagesAsync()).Single();65 await page.SetUserAgentAsync(UserAgentString);66 await page.GoToAsync(FacebookUrl, WaitUntilNavigation.Networkidle0);67 await page.ClickAsync("button[data-testid=cookie-policy-dialog-accept-button]");68 await page.WaitForSelectorAsync("button[data-testid=cookie-policy-dialog-accept-button]", new WaitForSelectorOptions { Hidden = true });69 await page.TypeAsync("#email", botSettings.Facebook.Login);70 await page.TypeAsync("#pass", botSettings.Facebook.Password);71 await page.ClickAsync("button[name=login]", new ClickOptions { ClickCount = 3 });72 await page.WaitForSelectorAsync("form[action^='/logout.php']");73 await page.GoToAsync("about:blank");74 logger.LogInformation("Logged to FB");75 }76 public async Task<IList<FacebookPost>> GetTimelinePosts()77 {78 var browser = await GetLaunchedBrowser();79 var page = (await browser.PagesAsync()).Single();80 await page.SetUserAgentAsync(UserAgentString);81 await page.GoToAsync(FacebookUserUrl);82 await page.WaitForSelectorAsync("div[data-pagelet='ProfileTimeline']");83 var sw = new Stopwatch();84 sw.Start();85 var loadedPostCount = 0;86 while (loadedPostCount < 10)87 {88 if (sw.Elapsed.Seconds > 120)89 {90 sw.Stop();91 await page.GoToAsync("about:blank");92 throw new InvalidOperationException();93 }94 loadedPostCount = await LoadTimelinePosts(page);...

Full Screen

Full Screen

GetPage.cs

Source:GetPage.cs Github

copy

Full Screen

...48 //{ "user-agent", "Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5355d Safari/8536.25" }49 };50 //en-GB,en-US;q=0.9,en;q=0.851 await PageResults.SetExtraHttpHeadersAsync(dic);52 await PageResults.SetUserAgentAsync("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36");53 foreach (var page in Pages)54 {55 page.DefaultTimeout = 0;56 await page.SetExtraHttpHeadersAsync(dic);57 await page.SetUserAgentAsync("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36");58 59 var response = await page.GoToAsync("https://www.bet365.com/#/AVR/B24/R^1/", navigation);60 //await page.SetCookieAsync(await page.GetCookiesAsync());61 if (!response.Ok)62 return false;63 }64 return await NavigateToResultsDiv();65 }66 catch67 {68 return false;69 }70 }71 private static async Task<bool> NavigateToResultsDiv()...

Full Screen

Full Screen

WebPage.cs

Source:WebPage.cs Github

copy

Full Screen

...29 Response response = await _page.GoToAsync(url, timeout, waitUntil);30 IWebResponse webResponse = new WebResponse(response);31 return webResponse;32 }33 public async Task SetUserAgentAsync(string userAgent)34 {35 await _page.SetUserAgentAsync(userAgent);36 }37 public async Task<string> GetContentAsync()38 {39 return await _page.GetContentAsync();40 }41 public async Task<IWebRequest> WaitForRequestAsync(Func<Request, bool> predicate, WaitForOptions options = null)42 {43 await ConfigurePage();44 Request request = await _page.WaitForRequestAsync(predicate, options);45 IWebRequest webRequest = new WebRequest(request);46 return webRequest;47 }48 public async Task<CookieParam[]> GetCookiesAsync(params string[] urls)49 {...

Full Screen

Full Screen

SetUserAgentTests.cs

Source:SetUserAgentTests.cs Github

copy

Full Screen

...12 [Fact]13 public async Task ShouldWork()14 {15 Assert.Contains("Mozilla", await Page.EvaluateFunctionAsync<string>("() => navigator.userAgent"));16 await Page.SetUserAgentAsync("foobar");17 var userAgentTask = Server.WaitForRequest("/empty.html", request => request.Headers["User-Agent"].ToString());18 await Task.WhenAll(19 userAgentTask,20 Page.GoToAsync(TestConstants.EmptyPage)21 );22 Assert.Equal("foobar", userAgentTask.Result);23 }24 [Fact]25 public async Task ShouldSimulateDeviceUserAgent()26 {27 await Page.GoToAsync(TestConstants.ServerUrl + "/mobile.html");28 Assert.Contains("Chrome", await Page.EvaluateExpressionAsync<string>("navigator.userAgent"));29 await Page.SetUserAgentAsync(TestConstants.IPhone.UserAgent);30 Assert.Contains("Safari", await Page.EvaluateExpressionAsync<string>("navigator.userAgent"));31 }32 }33}...

Full Screen

Full Screen

UserAgentPatcher.cs

Source:UserAgentPatcher.cs Github

copy

Full Screen

...5 public static class UserAgentPatcher6 {7 public static async Task SetupInterceptor(Browser browser, string userAgent)8 {9 async Task InterceptPage(Page page) => await page.SetUserAgentAsync(userAgent);10 var pages = await browser.PagesAsync();11 foreach (var page in pages) await InterceptPage(page);12 browser.TargetCreated += async (obj1, args1) =>13 {14 try15 {16 var target = args1.Target;17 var page = await target.PageAsync();18 if (page == null) return;19 await InterceptPage(page);20 }21 // Protocol error (Page.createIsolatedWorld): Could not create isolated world22 catch (PuppeteerException) { }23 };...

Full Screen

Full Screen

AnonymizeUaPlugin.cs

Source:AnonymizeUaPlugin.cs Github

copy

Full Screen

...21 var regex = new Regex(@"/\(([^)]+)\)/");22 ua = regex.Replace(ua, "(Windows NT 10.0; Win64; x64)");23 if (_customAction != null)24 ua = _customAction(ua);25 await page.SetUserAgentAsync(ua);26 }27 }28}...

Full Screen

Full Screen

SetUserAgentAsync

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 {9 Args = new string[] { "--no-sandbox" }10 };11 using (var browser = await Puppeteer.LaunchAsync(options))12 {13 var page = await browser.NewPageAsync();14 await page.SetUserAgentAsync("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36");15 }16 }17 }18}19using System;20using System.Threading.Tasks;21using PuppeteerSharp;22{23 {24 static async Task Main(string[] args)25 {26 {27 Args = new string[] { "--no-sandbox" }28 };29 using (var browser = await Puppeteer.LaunchAsync(options))30 {31 var page = await browser.NewPageAsync();32 await page.SetUserAgentAsync("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36");33 }34 }35 }36}37using System;38using System.Threading.Tasks;39using PuppeteerSharp;40{41 {42 static async Task Main(string[] args)43 {44 {45 Args = new string[] { "--no-sandbox" }46 };47 using (var browser = await Puppeteer.LaunchAsync(options))48 {49 var page = await browser.NewPageAsync();50 await page.SetUserAgentAsync("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML

Full Screen

Full Screen

SetUserAgentAsync

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 {9 };10 using (var browser = await Puppeteer.LaunchAsync(options))11 {12 var page = await browser.NewPageAsync();13 await page.SetUserAgentAsync("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36");14 await page.WaitForSelectorAsync("#detected_value");15 var userAgent = await page.EvaluateExpressionAsync<string>("document.querySelector('#detected_value').textContent");16 Console.WriteLine(userAgent);17 }18 }19 }20}21Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36

Full Screen

Full Screen

SetUserAgentAsync

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 {9 Args = new string[] { "--no-sandbox" }10 };11 using (var browser = await Puppeteer.LaunchAsync(options))12 {13 using (var page = await browser.NewPageAsync())14 {15 await page.SetUserAgentAsync("Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36");16 await page.ScreenshotAsync("path/to/save/screenshot.png");17 }18 }19 }20 }21}

Full Screen

Full Screen

SetUserAgentAsync

Using AI Code Generation

copy

Full Screen

1using PuppeteerSharp;2using System;3using System.Threading.Tasks;4{5 {6 public static async Task Main(string[] args)7 {8 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);9 var browser = await Puppeteer.LaunchAsync(new LaunchOptions10 {11 });12 var page = await browser.NewPageAsync();13 await page.SetUserAgentAsync("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.81 Safari/537.36");14 Console.ReadLine();15 }16 }17}

Full Screen

Full Screen

SetUserAgentAsync

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 Console.WriteLine("Hello World!");9 {10 Args = new string[] { "--start-maximized" }11 };12 var browser = await Puppeteer.LaunchAsync(options);13 var page = await browser.NewPageAsync();14 await page.SetUserAgentAsync("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36");15 await page.ScreenshotAsync("google.png");16 await browser.CloseAsync();17 }18 }19}20using System;21using System.Threading.Tasks;22using PuppeteerSharp;23{24 {25 static async Task Main(string[] args)26 {27 Console.WriteLine("Hello World!");28 {29 Args = new string[] { "--start-maximized" }30 };31 var browser = await Puppeteer.LaunchAsync(options);32 var page = await browser.NewPageAsync();33 await page.SetUserAgentAsync("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36");34 await page.ScreenshotAsync("google.png");35 await browser.CloseAsync();36 }37 }38}

Full Screen

Full Screen

SetUserAgentAsync

Using AI Code Generation

copy

Full Screen

1using PuppeteerSharp;2using System.Threading.Tasks;3{4 {5 static async Task Main(string[] args)6 {7 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);8 using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions9 {10 }))11 using (var page = await browser.NewPageAsync())12 {13 await page.SetUserAgentAsync("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36");14 }15 }16 }17}

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.

Most used method in Page

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful