How to use GoToAsync method of PuppeteerSharp.Page class

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

PuppeteerMethods.cs

Source:PuppeteerMethods.cs Github

copy

Full Screen

...37 {38 try39 {40 WaitUntilNavigation[] waitUntil = new[] { WaitUntilNavigation.Networkidle0, WaitUntilNavigation.Networkidle2, WaitUntilNavigation.DOMContentLoaded, WaitUntilNavigation.Load };41 await page.GoToAsync("http://www.google.com", new NavigationOptions { WaitUntil = waitUntil });42 var filePath = "D:\\PdfFiles";43 var fileName = Guid.NewGuid() + ".pdf";44 if (!Directory.Exists(filePath))45 Directory.CreateDirectory(filePath);46 await page.PdfAsync(Path.Combine(filePath, fileName));47 return new SuccessPuppeteerResult("Pdf Created Succesfully");48 }49 catch (Exception ex)50 {51 return new ErrorPuppeteerResult("Error Occured! Detail: " + ex.Message);52 }53 finally54 {55 CloseChromium(page);56 }57 }58 }59 public static async Task<PuppeteerResult> TakeScreenShot(string url)60 {61 using (var page = await OpenChromiumPage())62 {63 try64 {65 WaitUntilNavigation[] waitUntil = new[] { WaitUntilNavigation.Networkidle0, WaitUntilNavigation.Networkidle2, WaitUntilNavigation.DOMContentLoaded, WaitUntilNavigation.Load };66 await page.GoToAsync(url, new NavigationOptions { WaitUntil = waitUntil });67 var filePath = "D:\\Screenshots";68 var fileName = Guid.NewGuid() + ".png";69 if (!Directory.Exists(filePath))70 Directory.CreateDirectory(filePath);71 await page.SetViewportAsync(new ViewPortOptions72 {73 Width = 1280,74 Height = 72075 });76 await page.ScreenshotAsync(Path.Combine(filePath, fileName));77 return new SuccessPuppeteerResult("Screenshot has taken succesfully");78 }79 catch (Exception ex)80 {81 return new ErrorPuppeteerResult("Error Occured! Detail: " + ex.Message);82 }83 finally84 {85 CloseChromium(page);86 }87 }88 }89 public static async Task<string> TakeHtmlContent()90 {91 using (var page = await OpenChromiumPage())92 {93 WaitUntilNavigation[] waitUntil = new[] { WaitUntilNavigation.Networkidle0, WaitUntilNavigation.Networkidle2, WaitUntilNavigation.DOMContentLoaded, WaitUntilNavigation.Load };94 await page.GoToAsync("http://www.google.com", new NavigationOptions { WaitUntil = waitUntil });95 return await page.GetContentAsync();96 }97 }98 public static async Task<string> SetHtmlToPage()99 {100 using (var page = await OpenChromiumPage())101 {102 WaitUntilNavigation[] waitUntil = new[] { WaitUntilNavigation.Networkidle0, WaitUntilNavigation.Networkidle2, WaitUntilNavigation.DOMContentLoaded, WaitUntilNavigation.Load };103 await page.SetContentAsync("<div><h1>Hello World!</h1></div>");104 return await page.GetContentAsync();105 }106 }107 public static async Task<PuppeteerDataResult<string>> GetTitleOfPage(string url)108 {109 using (var page = await OpenChromiumPage())110 {111 try112 {113 WaitUntilNavigation[] waitUntil = new[] { WaitUntilNavigation.Networkidle0, WaitUntilNavigation.Networkidle2, WaitUntilNavigation.DOMContentLoaded, WaitUntilNavigation.Load };114 await page.GoToAsync(url, new NavigationOptions { WaitUntil = waitUntil });115 var title = await page.GetTitleAsync();116 return new SuccessPuppeteerDataResult<string>(title, "Get Title Successfully");117 }118 catch (Exception ex)119 {120 return new ErrorPuppeteerDataResult<string>("Error Occured! Detail: " + ex.Message);121 }122 finally123 {124 CloseChromium(page);125 }126 }127 }128 public static async Task<Frame[]> GetAllFrames()129 {130 using (var page = await OpenChromiumPage())131 {132 WaitUntilNavigation[] waitUntil = new[] { WaitUntilNavigation.Networkidle0, WaitUntilNavigation.Networkidle2, WaitUntilNavigation.DOMContentLoaded, WaitUntilNavigation.Load };133 await page.GoToAsync("https://www.google.com", new NavigationOptions { WaitUntil = waitUntil });134 return page.Frames;135 }136 }137 public static async Task<PuppeteerResult> LoginFacebook(string username, string password)138 {139 using (var page = await OpenChromiumPage())140 {141 try142 {143 WaitUntilNavigation[] waitUntil = new[] { WaitUntilNavigation.Networkidle0, WaitUntilNavigation.Networkidle2, WaitUntilNavigation.DOMContentLoaded, WaitUntilNavigation.Load };144 await page.GoToAsync("https://tr-tr.facebook.com/", new NavigationOptions { WaitUntil = waitUntil });145 await page.WaitForSelectorAsync("input#email");146 //You must change your facebook login informations.147 await page.TypeAsync("input#email", username);148 await page.TypeAsync("input#pass", password);149 await page.ClickAsync("button[name='login']");150 await page.WaitForNavigationAsync();151 var HtmlContent = await page.GetContentAsync();152 var Cookie = await page.GetCookiesAsync();153 var TitleOfPage = await page.GetTitleAsync();154 var filePath = "D:\\PdfFiles";155 var fileName = Guid.NewGuid() + ".pdf";156 if (!Directory.Exists(filePath))157 Directory.CreateDirectory(filePath);158 await page.PdfAsync(Path.Combine(filePath, fileName));159 return new SuccessPuppeteerResult("Pdf Created Succesfully");160 }161 catch (Exception ex)162 {163 return new ErrorPuppeteerResult("Error Occured! Detail: " + ex.Message);164 }165 finally166 {167 CloseChromium(page);168 }169 }170 }171 public static async Task<List<string>> VideoLinkList(Page page)172 {173 WaitUntilNavigation[] waitUntil = new[] { WaitUntilNavigation.Networkidle0, WaitUntilNavigation.Networkidle2, WaitUntilNavigation.DOMContentLoaded, WaitUntilNavigation.Load }; 174 var next = @"document.getElementById('pnnext')";175 var nexts = await page.EvaluateExpressionAsync<object>(next);176 var linkList = new List<string>();177 var isLastPage = (nexts == null);178 while ((nexts != null) || !isLastPage)179 {180 var jsSelectAllAnchors = @"Array.from(document.querySelectorAll('.g'))";181 var urls = await page.EvaluateExpressionAsync<object[]>(jsSelectAllAnchors);182 for (int i = 0; i < urls.Length; i++)183 {184 var query = $"document.querySelectorAll('.g')[{i}].getElementsByTagName('a')[0].href";185 linkList.Add(await page.EvaluateExpressionAsync<string>(query));186 }187 nexts = await page.EvaluateExpressionAsync<object>(next);188 if (nexts != null)189 {190 var nextHref = @"document.getElementById('pnnext').href";191 var nextHrefUrl = await page.EvaluateExpressionAsync<string>(nextHref);192 isLastPage = (nexts == null) && !string.IsNullOrEmpty(nextHrefUrl);193 await page.GoToAsync(nextHrefUrl, new NavigationOptions { WaitUntil = waitUntil });194 nexts = await page.EvaluateExpressionAsync<object>(next);195 }196 else197 {198 isLastPage = true;199 }200 }201 return linkList;202 } 203 public static async Task<PuppeteerDataResult<List<string>>> GetVideoSearchVideoResultUrlList(string url, string searchWord)204 {205 using (var page = await OpenChromiumPage())206 {207 WaitUntilNavigation[] waitUntil = new[] { WaitUntilNavigation.Networkidle0, WaitUntilNavigation.Networkidle2, WaitUntilNavigation.DOMContentLoaded, WaitUntilNavigation.Load };208 await page.GoToAsync(url, new NavigationOptions { WaitUntil = waitUntil });209 await SearchOnGoogle(searchWord, page);210 //Click Video Tab211 var videoTabElement = @"document.getElementsByClassName('hdtb-mitem')[4].getElementsByTagName('a')[0].href";212 var videoTabLink = await page.EvaluateExpressionAsync<string>(videoTabElement); 213 await page.GoToAsync(videoTabLink, new NavigationOptions { WaitUntil = waitUntil });214 215 var result= await VideoLinkList(page); 216 return new SuccessPuppeteerDataResult<List<string>>(result, "Get Title Successfully"); 217 }218 }219 public static async Task<PuppeteerDataResult<string>> GetSearchStaticticDetail(string url, string searchWord)220 {221 using (var page = await OpenChromiumPage())222 {223 WaitUntilNavigation[] waitUntil = new[] { WaitUntilNavigation.Networkidle0, WaitUntilNavigation.Networkidle2, WaitUntilNavigation.DOMContentLoaded, WaitUntilNavigation.Load };224 await page.GoToAsync(url, new NavigationOptions { WaitUntil = waitUntil });225 await SearchOnGoogle(searchWord, page);226 var jsExpression = @"document.querySelectorAll('#result-stats')[0].innerHTML";227 var result = await page.EvaluateExpressionAsync<string>(jsExpression);228 return new SuccessPuppeteerDataResult<string>(result, "");229 }230 }231 private static async Task SearchOnGoogle(string searchWord, Page page)232 {233 WaitUntilNavigation[] waitUntil = new[] { WaitUntilNavigation.Networkidle0, WaitUntilNavigation.Networkidle2, WaitUntilNavigation.DOMContentLoaded, WaitUntilNavigation.Load };234 //Search Text Input235 await page.WaitForSelectorAsync("input[name='q']");236 await page.TypeAsync("input[name='q']", searchWord);237 //Search on Google Button and Click Operation238 await page.WaitForSelectorAsync("input[name='btnK']");...

Full Screen

Full Screen

SaveWebPage.xaml.cs

Source:SaveWebPage.xaml.cs Github

copy

Full Screen

...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}");107108 pdfOptions.Width = $"{width}px";109 pdfOptions.Height = $"{height}px";110111 pdfOptions.HeaderTemplate = ""; //页眉文本112 pdfOptions.Landscape = false; //纸张方向 false-垂直 true-水平 ...

Full Screen

Full Screen

ReportService.cs

Source:ReportService.cs Github

copy

Full Screen

...64 var browser = await GetBrowser();6566 using (var page = await browser.NewPageAsync())67 {68 //await page.GoToAsync("http://localhost:59375/");69 //await page.GoToAsync("https://github.com/kblok/puppeteer-sharp");70 //await page.SetContentAsync("<html><head></head><body>test</body></html>");71 //await page.SetContentAsync(html);7273 htmlOrUrl = fromUrl ? htmlOrUrl : "data:text/html," + htmlOrUrl;7475 await page.GoToAsync(htmlOrUrl, new NavigationOptions()76 {77 WaitUntil = new WaitUntilNavigation[] { WaitUntilNavigation.Load, WaitUntilNavigation.Networkidle0 },78 Timeout = 600000 // Timeoutを10分(初期値は30秒)79 });8081 var stream = await page.PdfStreamAsync(option);82 return stream;83 }84 }8586 /// <summary>87 /// デフォルトのPdfオプションを作成する。88 /// </summary>89 /// <returns></returns> ...

Full Screen

Full Screen

TimeTrackingController.cs

Source:TimeTrackingController.cs Github

copy

Full Screen

...30 {31 return;32 }33 34 await page.GoToAsync(@"https://timetracker.bairesdev.com/");35 await page.TypeAsync("#ctl00_ContentPlaceHolder_UserNameTextBox", tracking.User);36 await page.TypeAsync("#ctl00_ContentPlaceHolder_PasswordTextBox", tracking.Password);37 await page.ClickAsync("#ctl00_ContentPlaceHolder_LoginButton");38 await page.GoToAsync(@"https://timetracker.bairesdev.com/CargaTimeTracker.aspx");39 40 await page.EvaluateExpressionAsync($@"document.querySelector('#ctl00_ContentPlaceHolder_txtFrom').value = null");41 await page.TypeAsync("#ctl00_ContentPlaceHolder_txtFrom", tracking.Date, new TypeOptions{ Delay = 30 });42 var dropProject = await page.QuerySelectorAsync("#ctl00_ContentPlaceHolder_idProyectoDropDownList");43 await dropProject.ClickAsync();44 45 var children = await dropProject.QuerySelectorAllAsync("option");46 await children[2].ClickAsync();47 48 await page.ClickAsync("#ctl00_ContentPlaceHolder_TiempoTextBox");49 await page.TypeAsync("#ctl00_ContentPlaceHolder_TiempoTextBox", tracking.Hours.ToString(), new TypeOptions{ Delay = 30 });50 await page.ClickAsync("#ctl00_ContentPlaceHolder_idTipoAsignacionDropDownList");51 //await page.FocusAsync("#ctl00_ContentPlaceHolder_idTipoAsignacionDropDownList");52 //await page.SelectAsync("#ctl00_ContentPlaceHolder_idTipoAsignacionDropDownList", tracking.AssignmentType);...

Full Screen

Full Screen

InstagramService.cs

Source:InstagramService.cs Github

copy

Full Screen

...25 using (var browser = await Puppeteer.LaunchAsync(optionsLaunch))26 using (var page = await browser.NewPageAsync())27 {28 var profileUrl = $"https://www.instagram.com/{profile}/";29 await page.GoToAsync(profileUrl);30 var jsSelectAllAnchors = @"Array.from(document.querySelectorAll('article a')).map(el => {31 const url = el.href;32 const child = el.firstChild.firstChild.firstChild33 return {34 link: url, 35 description: child.alt, 36 src: child.src37 }38 })";39 var images = await page.EvaluateExpressionAsync<Image[]>(jsSelectAllAnchors);40 result = images;41 await page.CloseAsync();42 }43 }...

Full Screen

Full Screen

WebBrowser.cs

Source:WebBrowser.cs Github

copy

Full Screen

...11 using (var browser = await GetBrowser())12 {13 using (var page = await browser.NewPageAsync())14 {15 await page.GoToAsync(url);16 var bytes = await page.PdfDataAsync(new PdfOptions { MarginOptions = new PuppeteerSharp.Media.MarginOptions { Top = "1cm", Bottom = "1cm" } });17 var browserPath = ApiFactory.GetBrowserPath();18 var pdfPath = Path.Combine(browserPath, "pdf");19 if (!Directory.Exists(pdfPath))20 {21 Directory.CreateDirectory(pdfPath);22 }23 var pdfFilePath = Path.Combine(pdfPath, Path.GetFileNameWithoutExtension(Path.GetTempFileName()) + ".pdf");24 await File.WriteAllBytesAsync(pdfFilePath, bytes);25 var fileInfo = new FileInfo(pdfFilePath);26 return fileInfo;27 }28 }29 }30 31 public async Task<string> Content(string url)32 {33 using (var browser = await GetBrowser())34 {35 using (var page = await browser.NewPageAsync())36 {37 await page.GoToAsync(url);38 var result = await page.GetContentAsync();39 return result;40 }41 }42 }43 public async Task<byte[]> Screenshot(string url)44 {45 using (var browser = await GetBrowser())46 {47 using (var page = await browser.NewPageAsync())48 {49 await page.GoToAsync(url);50 var result = await page.ScreenshotDataAsync();51 return result;52 }53 }54 }55 }56}...

Full Screen

Full Screen

BrowserTests.cs

Source:BrowserTests.cs Github

copy

Full Screen

...44 {45 if (e.Message.Type == ConsoleType.Error)46 hasError = true;47 }48 await page.GoToAsync(BaseAddress);49 var selector = await page.WaitForSelectorAsync("div.table-responsive > table > tbody > tr:nth-child(1) > td:nth-child(3)");50 (await selector.InnerTextAsync()).ShouldBe("Astrix Mariette");51 hasError.ShouldBeFalse();52 await PrintPerf(page);53 }54 }55}...

Full Screen

Full Screen

DocumentsController.cs

Source:DocumentsController.cs Github

copy

Full Screen

...18 public static async Task<Stream> GeneratePdfAsync(string url, bool landscape) {19 var options = new LaunchOptions { Headless = true, ExecutablePath = @"/usr/bin/chromium-browser", Args = new string[] { "--no-sandbox" } };20 using (var browser = await Puppeteer.LaunchAsync(options))21 using (var page = await browser.NewPageAsync()) {22 await page.GoToAsync(url);23 return await page.PdfStreamAsync(new PdfOptions() { Format = PuppeteerSharp.Media.PaperFormat.A4, Landscape = landscape, OmitBackground = true, PrintBackground = true });24 }25 }26 }27}...

Full Screen

Full Screen

GoToAsync

Using AI Code Generation

copy

Full Screen

1var page = await browser.NewPageAsync();2var page = await browser.NewPageAsync();3var page = await browser.NewPageAsync();4var page = await browser.NewPageAsync();5var page = await browser.NewPageAsync();6var page = await browser.NewPageAsync();7var page = await browser.NewPageAsync();8var page = await browser.NewPageAsync();9var page = await browser.NewPageAsync();

Full Screen

Full Screen

GoToAsync

Using AI Code Generation

copy

Full Screen

1var browser = await Puppeteer.LaunchAsync(new LaunchOptions2{3});4var page = await browser.NewPageAsync();5await page.ScreenshotAsync("google.png");6await browser.CloseAsync();7var browser = await Puppeteer.LaunchAsync(new LaunchOptions8{9});10var page = await browser.NewPageAsync();11await page.ScreenshotAsync("google.png");12await browser.CloseAsync();13var browser = await Puppeteer.LaunchAsync(new LaunchOptions14{15});16var page = await browser.NewPageAsync();17await page.ScreenshotAsync("google.png");18await browser.CloseAsync();19var browser = await Puppeteer.LaunchAsync(new LaunchOptions20{21});22var page = await browser.NewPageAsync();23await page.ScreenshotAsync("google.png");24await browser.CloseAsync();25var browser = await Puppeteer.LaunchAsync(new LaunchOptions26{27});28var page = await browser.NewPageAsync();29await page.ScreenshotAsync("google.png");

Full Screen

Full Screen

GoToAsync

Using AI Code Generation

copy

Full Screen

1using System.Threading.Tasks;2using PuppeteerSharp;3{4 {5 static async Task Main(string[] args)6 {7 {8 };9 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);10 using (var browser = await Puppeteer.LaunchAsync(options))11 {12 using (var page = await browser.NewPageAsync())13 {14 }15 }16 }17 }18}

Full Screen

Full Screen

GoToAsync

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 static async Task Main(string[] args)6 {7 {8 ExecutablePath = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"9 };10 using (var browser = await Puppeteer.LaunchAsync(options))11 {12 using (var page = await browser.NewPageAsync())13 {14 }15 }16 }17}18using System;19using System.Threading.Tasks;20using PuppeteerSharp;21{22 static async Task Main(string[] args)23 {24 {25 ExecutablePath = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"26 };27 using (var browser = await Puppeteer.LaunchAsync(options))28 {29 using (var page = await browser.NewPageAsync())30 {31 await page.WaitForTimeoutAsync(5000);32 }33 }34 }35}36using System;37using System.Threading.Tasks;38using PuppeteerSharp;39{40 static async Task Main(string[] args)41 {42 {43 ExecutablePath = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"44 };45 using (var browser = await Puppeteer.LaunchAsync(options))46 {47 using (var page = await browser.NewPageAsync())48 {

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