How to use NewPageAsync method of PuppeteerSharp.BrowserContext class

Best Puppeteer-sharp code snippet using PuppeteerSharp.BrowserContext.NewPageAsync

PuppeteerBrowserBuilder.cs

Source:PuppeteerBrowserBuilder.cs Github

copy

Full Screen

...355 return await _browserContext.PagesAsync();356 }357 async Task<string> IPuppeteerBrowser.GetFramePage(string iframeSrc)358 {359 using (var multiVideopage = await _browserContext.NewPageAsync())360 {361 await SetPageOptions(multiVideopage);362 await multiVideopage.GoToAsync(iframeSrc, Convert.ToInt32(_puppeteerContext.PageLoadTimeout.TotalMilliseconds), new WaitUntilNavigation[] { WaitUntilNavigation.DOMContentLoaded, WaitUntilNavigation.Load, WaitUntilNavigation.Networkidle0, WaitUntilNavigation.Networkidle2 });363 var data = await multiVideopage.GetContentAsync();364 return data;365 }366 }367 async Task<string> IPuppeteerBrowser.GetFramePage(Page page, string frameName)368 {369 var googlAdsFrame1 = page.Frames.ToList().FirstOrDefault(x => x.Name == frameName);370 if (googlAdsFrame1 == null)371 {372 return null;373 }374 return await googlAdsFrame1.GetContentAsync();375 }376 377 async Task<string> IPuppeteerBrowser.GetVideoAdsOnUrl(Page page, string xPath)378 {379 var elementToclick = await page.WaitForXPathAsync(xPath);380 if (elementToclick != null) 381 {382 await elementToclick.ClickAsync();383 return await page.EvaluateFunctionAsync<string>("() => navigator.clipboard.readText()");384 }385 _logger.Debug("GetVideoAdsOnUrl: elementToclick is null");386 return null;387 }388 /// <summary>389 /// Returns IpDetails by the specified url390 /// </summary>391 /// <param name="ipFetcherUrl">The ip details provider url.</param>392 /// <returns>The instance of <see cref="IpDetails"></see></returns>393 async Task<IpDetails> IPuppeteerBrowser.GetIpDetails(string ipFetcherUrl)394 {395 IpDetails ipDetails = await GetIpDetailsInternal(ipFetcherUrl);396 return ipDetails ?? new IpDetails397 {398 City = "N/A",399 ContinentName = "N/A",400 CountryCode = "N/A",401 CountryName = "N/A",402 IpAddress = "127.0.0.1",403 State = "N/A",404 ContinentCode = "N/A"405 };406 }407 /// <summary>408 /// Returns IpDetails by the specified url and, in case of error, returns the default country code and country name409 /// </summary>410 /// <param name="ipFetcherUrl">The ip details provider url.</param>411 /// <param name="defaultCountryCode">The country code tu return default details.</param>412 /// <returns>The instance of <see cref="IpDetails"></see></returns>413 async Task<IpDetails> IPuppeteerBrowser.GetIpDetails(string ipFetcherUrl, string defaultCountryCode)414 {415 IpDetails ipDetails = await GetIpDetailsInternal(ipFetcherUrl);416 return ipDetails ?? new IpDetails417 {418 City = "N/A",419 ContinentName = "N/A",420 CountryCode = defaultCountryCode,421 CountryName = References.Countries[defaultCountryCode],422 IpAddress = "127.0.0.1",423 State = "N/A",424 ContinentCode = "N/A"425 };426 }427 async Task<string> IPuppeteerBrowser.GetPageContent(string stringUrl, params WaitUntilNavigation[] waitUntilNavigations)428 {429 return await GetPageContentInternalAsync(stringUrl, waitUntilNavigations);430 }431 private async Task SetPageOptions(Page page)432 {433 var viewPortOptions = new ViewPortOptions434 { Width = _browserConfig.WindowWidth, Height = _browserConfig.WindowHeight };435 await page.SetViewportAsync(viewPortOptions);436 if (!string.IsNullOrWhiteSpace(_puppeteerContext.ProxyUserName))437 {438 await page.AuthenticateAsync(new Credentials439 {440 Username = _puppeteerContext.ProxyUserName,441 Password = _puppeteerContext.ProxyPwd442 });443 }444 }445 async Task<Page> IPuppeteerBrowser.GetPage(string url, TimeSpan? timeoutPageLoad, params WaitUntilNavigation[] waitUntilNavigations)446 {447 var page = await GoToPageAsync(url, timeoutPageLoad, waitUntilNavigations);448 if (_overridePermissions?.Any() ?? false)449 {450 await page.BrowserContext.OverridePermissionsAsync(page.Url,451 new []452 {453 OverridePermission.ClipboardWrite, OverridePermission.ClipboardRead,454 OverridePermission.AccessibilityEvents, OverridePermission.BackgroundSync,455 OverridePermission.Geolocation, OverridePermission.Microphone, OverridePermission.Notifications,456 OverridePermission.PaymentHandler/*, OverridePermission.Push*/457 });458 }459 return page;460 }461 async Task<string> IPuppeteerBrowser.GetScrolledPage(string url, int maxScroll, params WaitUntilNavigation[] waitUntilNavigations)462 {463 var pageResult = string.Empty;464 try465 {466 using (var page = await GoToPageAsync(url, null, waitUntilNavigations))467 {468 await ScrollPageSync(page, TimeSpan.FromMilliseconds(100));469 pageResult = await page.GetContentAsync();470 }471 }472 catch (Exception ex)473 {474 _logger.Error(ex);475 }476 return pageResult;477 }478 async Task IPuppeteerBrowser.ScrollPageSync(Page page, int maxScroll = 40000, int step = 200)479 {480 await ScrollPageSync(page, TimeSpan.FromMilliseconds(100), maxScroll, step);481 }482 /// <summary>483 /// Return state of page permission. Exmp: permissionName=clipboard-read484 /// </summary>485 /// <returns></returns>486 async Task<string> IPuppeteerBrowser.GetPagePermission(Page page, string permissionName)487 {488 return await page.EvaluateFunctionAsync<string>($"name => navigator.permissions.query({permissionName}).then(result => result.state)");489 }490 public async Task ScrollPageSync(Page page, TimeSpan stepDelay, int maxScroll = 40000, int step = 200)491 {492 var height = await page.EvaluateExpressionAsync<int>(@"document.body.scrollHeight");493 var x = 0;494 while (x < height && x <= maxScroll)495 {496 height = await page.EvaluateExpressionAsync<int>(@"document.body.scrollHeight");497 x += 200;498 await _delayService.DelayAsync(stepDelay);499 await page.EvaluateExpressionAsync($"window.scrollTo(0, {x});");500 }501 }502 private async Task<Page> GoToPageAsync(string stringUrl, TimeSpan? timeSpan, params WaitUntilNavigation[] waitUntilNavigations)503 {504 var page = await _browserContext.NewPageAsync();505 await page.SetCacheEnabledAsync(_puppeteerContext.PageCacheEnabled);506 await page.SetJavaScriptEnabledAsync(true);507 if (_puppeteerContext.PageEvents)508 {509 page.Error += Page_Error;510 page.PageError += Page_PageError;511 page.Console += Page_Info;512 page.Request += Page_Request;513 }514 if (_puppeteerContext.DialogHandler != null)515 {516 page.Dialog += _puppeteerContext.DialogHandler;517 }518 await SetPageOptions(page);519 var resp = await page.GoToAsync(stringUrl,520 Convert.ToInt32((timeSpan ?? TimeSpan.FromSeconds(30)).Milliseconds), waitUntilNavigations);521 LogGoToResponse(stringUrl, resp);522 return page;523 }524 private void Page_PageError(object sender, PageErrorEventArgs e)525 {526 _logger.Error(e.Message);527 }528 private void Page_Request(object sender, RequestEventArgs e)529 {530 _logger.Debug($"{e.Request?.Method}:{e.Request?.ResourceType.ToString()}:{e.Request?.Url}");531 }532 private void LogGoToResponse(string stringUrl, Response resp)533 {534 if (resp != null)535 {536 var respLogEvent = new LogEventInfo(LogLevel.Info, string.Empty, $"goto response to {stringUrl}");537 respLogEvent.Properties["FromCache"] = resp.FromCache;538 respLogEvent.Properties["Url"] = resp.Url;539 respLogEvent.Properties["RemoteAddress.IP"] = resp.RemoteAddress?.IP;540 respLogEvent.Properties["RemoteAddress.Port"] = resp.RemoteAddress?.Port;541 respLogEvent.Properties["Request.RequestId"] = resp.Request?.RequestId;542 respLogEvent.Properties["Status"] = resp.Status;543 respLogEvent.Properties["Ok"] = resp.Ok;544 respLogEvent.Properties["FromServiceWorker"] = resp.FromServiceWorker;545 if (resp.Headers != null)546 {547 foreach (var header in resp.Headers)548 {549 respLogEvent.Properties[$"Header:{header.Key}"] = header.Value;550 }551 }552 _logger.Log(respLogEvent);553 }554 }555 private void Page_Info(object sender, ConsoleEventArgs e)556 {557 _logger.Info($"{e.Message.Type}: {e.Message.Text}");558 }559 private void Page_Error(object sender, PuppeteerSharp.ErrorEventArgs e)560 {561 _logger.Error(e.Error);562 }563 public void Dispose()564 {565 _logger.Info($"Disposing browser {_browser.Process.Id}");566 _browser?.Dispose();567 }568 private string StripHtmlTags(string input) => RegexStripHtmlTags.Replace(input, string.Empty); 569 private async Task<string> GetPageContentInternalAsync(string stringUrl, params WaitUntilNavigation[] waitUntilNavigations)570 {571 using (var page = await _browserContext.NewPageAsync())572 {573 await SetPageOptions(page);574 var resp = await page.GoToAsync(stringUrl, null, waitUntilNavigations);575 LogGoToResponse(stringUrl, resp);576 return await page.GetContentAsync();577 }578 }579 private async Task<IpDetails> GetIpDetailsInternal(string ipFetcherUrl)580 {581 IpDetails ipDetails = null;582 try583 {584 var ipPageSource = await GetPageContentInternalAsync(ipFetcherUrl, WaitUntilNavigation.Networkidle0);585 _logger.Info(ipPageSource);...

Full Screen

Full Screen

Browser.cs

Source:Browser.cs Github

copy

Full Screen

...15 /// An example of using a <see cref="Browser"/> to create a <see cref="Page"/>:16 /// <code>17 /// <![CDATA[18 /// var browser = await Puppeteer.LaunchAsync(new LaunchOptions());19 /// var page = await browser.NewPageAsync();20 /// await page.GoToAsync("https://example.com");21 /// await browser.CloseAsync();22 /// ]]>23 /// </code>24 /// An example of disconnecting from and reconnecting to a <see cref="Browser"/>:25 /// <code>26 /// <![CDATA[27 /// var browser = await Puppeteer.LaunchAsync(new LaunchOptions());28 /// var browserWSEndpoint = browser.WebSocketEndpoint;29 /// browser.Disconnect();30 /// var browser2 = await Puppeteer.ConnectAsync(new ConnectOptions { BrowserWSEndpoint = browserWSEndpoint });31 /// await browser2.CloseAsync();32 /// ]]>33 /// </code>34 /// </example>35 public class Browser : IDisposable36 {37 /// <summary>38 /// Time in milliseconds for chromium process to exit gracefully.39 /// </summary>40 private const int CloseTimeout = 5000;41 /// <summary>42 /// Initializes a new instance of the <see cref="Browser"/> class.43 /// </summary>44 /// <param name="connection">The connection</param>45 /// <param name="contextIds">The context ids></param>46 /// <param name="ignoreHTTPSErrors">The option to ignoreHTTPSErrors</param>47 /// <param name="defaultViewport">Default viewport</param>48 /// <param name="chromiumProcess">The Chromium process</param>49 public Browser(50 Connection connection,51 string[] contextIds,52 bool ignoreHTTPSErrors,53 ViewPortOptions defaultViewport,54 ChromiumProcess chromiumProcess)55 {56 Connection = connection;57 IgnoreHTTPSErrors = ignoreHTTPSErrors;58 DefaultViewport = defaultViewport;59 TargetsMap = new Dictionary<string, Target>();60 ScreenshotTaskQueue = new TaskQueue();61 DefaultContext = new BrowserContext(Connection, this, null);62 _contexts = contextIds.ToDictionary(keySelector: contextId => contextId,63 elementSelector: contextId => new BrowserContext(Connection, this, contextId));64 Connection.Closed += (object sender, EventArgs e) => Disconnected?.Invoke(this, new EventArgs());65 Connection.MessageReceived += Connect_MessageReceived;66 _chromiumProcess = chromiumProcess;67 _logger = Connection.LoggerFactory.CreateLogger<Browser>();68 }69 #region Private members70 internal readonly Dictionary<string, Target> TargetsMap;71 private readonly Dictionary<string, BrowserContext> _contexts;72 private readonly ILogger<Browser> _logger;73 private readonly ChromiumProcess _chromiumProcess;74 private Task _closeTask;75 #endregion76 #region Properties77 /// <summary>78 /// 79 /// </summary>80 public event EventHandler Closed;81 /// <summary>82 /// Raised when puppeteer gets disconnected from the Chromium instance. This might happen because one of the following83 /// - Chromium is closed or crashed84 /// - <see cref="Disconnect"/> method was called85 /// </summary>86 public event EventHandler Disconnected;87 /// <summary>88 /// Raised when the url of a target changes89 /// </summary>90 public event EventHandler<TargetChangedArgs> TargetChanged;91 /// <summary>92 /// Raised when a target is created, for example when a new page is opened by <c>window.open</c> <see href="https://developer.mozilla.org/en-US/docs/Web/API/Window/open"/> or <see cref="NewPageAsync"/>.93 /// </summary>94 public event EventHandler<TargetChangedArgs> TargetCreated;95 /// <summary>96 /// Raised when a target is destroyed, for example when a page is closed97 /// </summary>98 public event EventHandler<TargetChangedArgs> TargetDestroyed;99 /// <summary>100 /// Gets the Browser websocket url101 /// </summary>102 /// <remarks>103 /// Browser websocket endpoint which can be used as an argument to <see cref="Puppeteer.ConnectAsync(ConnectOptions, ILoggerFactory)"/>.104 /// The format is <c>ws://${host}:${port}/devtools/browser/[id]</c>105 /// You can find the <c>webSocketDebuggerUrl</c> from <c>http://${host}:${port}/json/version</c>.106 /// Learn more about the devtools protocol <see href="https://chromedevtools.github.io/devtools-protocol"/> 107 /// and the browser endpoint <see href="https://chromedevtools.github.io/devtools-protocol/#how-do-i-access-the-browser-target"/>108 /// </remarks>109 public string WebSocketEndpoint => Connection.Url;110 /// <summary>111 /// Gets the spawned browser process. Returns <c>null</c> if the browser instance was created with <see cref="Puppeteer.ConnectAsync(ConnectOptions, ILoggerFactory)"/> method.112 /// </summary>113 public Process Process => _chromiumProcess?.Process;114 /// <summary>115 /// Gets or Sets whether to ignore HTTPS errors during navigation116 /// </summary>117 public bool IgnoreHTTPSErrors { get; set; }118 /// <summary>119 /// Gets a value indicating if the browser is closed120 /// </summary>121 public bool IsClosed => _closeTask != null && _closeTask.IsCompleted && _closeTask.Exception != null;122 /// <summary>123 /// Returns the default browser context. The default browser context can not be closed.124 /// </summary>125 /// <value>The default context.</value>126 public BrowserContext DefaultContext { get; }127 internal TaskQueue ScreenshotTaskQueue { get; set; }128 internal Connection Connection { get; }129 internal ViewPortOptions DefaultViewport { get; }130 #endregion131 #region Public Methods132 /// <summary>133 /// Creates a new page134 /// </summary>135 /// <returns>Task which resolves to a new <see cref="Page"/> object</returns>136 public Task<Page> NewPageAsync() => DefaultContext.NewPageAsync();137 /// <summary>138 /// Returns An Array of all active targets139 /// </summary>140 /// <returns>An Array of all active targets</returns>141 public Target[] Targets() => TargetsMap.Values.Where(target => target.IsInitialized).ToArray();142 /// <summary>143 /// A target associated with the browser.144 /// </summary>145 public Target Target => Targets().FirstOrDefault(t => t.Type == TargetType.Browser);146 /// <summary>147 /// Creates a new incognito browser context. This won't share cookies/cache with other browser contexts.148 /// </summary>149 /// <returns>Task which resolves to a new <see cref="BrowserContext"/> object</returns>150 /// <example>151 /// <code>152 /// <![CDATA[153 /// using(var browser = await Puppeteer.LaunchAsync(new LaunchOptions()))154 /// {155 /// // Create a new incognito browser context.156 /// var context = await browser.CreateIncognitoBrowserContextAsync();157 /// // Create a new page in a pristine context.158 /// var page = await context.NewPageAsync();159 /// // Do stuff160 /// await page.GoToAsync("https://example.com");161 /// }162 /// ]]>163 /// </code>164 /// </example>165 public async Task<BrowserContext> CreateIncognitoBrowserContextAsync()166 {167 var response = await Connection.SendAsync<CreateBrowserContextResponse>("Target.createBrowserContext", new { }).ConfigureAwait(false);168 var context = new BrowserContext(Connection, this, response.BrowserContextId);169 _contexts[response.BrowserContextId] = context;170 return context;171 }172 /// <summary>...

Full Screen

Full Screen

UCFullPageScreenShot.cs

Source:UCFullPageScreenShot.cs Github

copy

Full Screen

...147 //if (saveHis)148 //{149 // browserContext = await browser.CreateIncognitoBrowserContextAsync();150 //}151 var page = await browserContext.NewPageAsync();152 await page.SetUserAgentAsync(_userAgent);153 await page.SetViewportAsync(new ViewPortOptions154 {155 Width = Screen.PrimaryScreen.WorkingArea.Width,156 Height = Screen.PrimaryScreen.WorkingArea.Height157 });158 159 if (!changeCountry.Contains("请选择") && _CountryModels.Any())160 {161 OnShowTooltipInfo("初始化首页内容,开始切换国家");162 //var zips = Properties.Resources.zip.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);163 //var zip = zips.OrderBy(m => Guid.NewGuid()).First(); 164 await page.GoToAsync("https://www.amazon.com/");165 var pagetitle = await page.GetTitleAsync();...

Full Screen

Full Screen

VkBrwUserFactory.cs

Source:VkBrwUserFactory.cs Github

copy

Full Screen

...30 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);31 LaunchOptions browserOptions = new LaunchOptions {Headless = false, Args = new string[] {"--lang=ru"}};32 Browser brw = await Puppeteer.LaunchAsync(browserOptions);33 BrowserContext userContext = await brw.CreateIncognitoBrowserContextAsync();34 Page userPage = await userContext.NewPageAsync();35 await userPage.SetViewportAsync(new ViewPortOptions36 {37 Width = 1024,38 Height = 76839 });40 await userPage.SetUserAgentAsync("Mozilla / 5.0(Windows NT 10.0; Win64; x64) AppleWebKit / 537.36(KHTML, like Gecko) Chrome / 74.0.3723.0 Safari / 537.36");41 user.Communitites = await GetCommunities(userContext, userPage, user);42 bool successParse = long.TryParse(user.ProfileLink.Split('/').LastOrDefault()?.Substring(2), out long parseResult);43 user.UserId = successParse ? parseResult : default;44 await userPage.CloseAsync();45 await userContext.CloseAsync();46 return user;47 }48 public async Task<List<VkBrwCommunity>> GetCommunities(BrowserContext userContext, Page userPage, VkBrwUser user)49 {50 List<VkBrwCommunity> nwPages = new List<VkBrwCommunity>();51 await userPage.GoToAsync(user.ProfileLink);52 ElementHandle userIsLoaded = await userPage.WaitForSelectorAsync("#page_info_wrap.page_info_wrap");53 ElementHandle[] hiddenProfileBlock = await userPage.QuerySelectorAllAsync("h5.profile_deleted_text");54 if (hiddenProfileBlock.Length == 0)55 {56 ElementHandle idolsLoaded = await userPage.WaitForSelectorAsync("#profile_idols");57 // Интересные страницы58 ElementHandle[] noteworthyPagesBlock = await userPage.QuerySelectorAllAsync("#profile_idols.module.clear.page_list_module._module");59 if (noteworthyPagesBlock.Length == 1)60 {61 ElementHandle noteworthyPages = noteworthyPagesBlock.First();62 ElementHandle[] noteworthyPagesHeaderBlock = await noteworthyPages.QuerySelectorAllAsync("a.module_header");63 if (noteworthyPagesHeaderBlock.Length == 1)64 {65 ClickOptions clickOptions = new ClickOptions { Delay = new Random().Next(30, 100) };66 ElementHandle noteworthyPagesLinkElement = noteworthyPagesHeaderBlock.First();67 await noteworthyPagesLinkElement.ClickAsync(clickOptions);68 ElementHandle noteworthyPagesIsOpened = await userPage.WaitForSelectorAsync("#fans_rowsidols.fans_rows.fans_idols");69 ElementHandle[] closeBlock = await userPage.QuerySelectorAllAsync("div.box_x_button");70 if (closeBlock.Length == 1)71 {72 ElementHandle[] pagesCountBlock = await userPage.QuerySelectorAllAsync("span.ui_box_header_cnt");73 if (pagesCountBlock.Length == 1)74 {75 ElementHandle pagesTotalCountElement = pagesCountBlock.First();76 string pagesTotalCountValue = await pagesTotalCountElement.EvaluateFunctionAsync<string>("('span', span => span.innerText)");77 if (!string.IsNullOrEmpty(pagesTotalCountValue))78 {79 bool pagesTotalCountReceived = int.TryParse(pagesTotalCountValue, out int pagesTotalCount);80 if (pagesTotalCountReceived && pagesTotalCount > 0)81 {82 ElementHandle[] pagesVisibleElements = await userPage.QuerySelectorAllAsync("div.fans_idol_row.inl_bl");83 if (pagesVisibleElements.Length < pagesTotalCount)84 {85 PressOptions pressOptions = new PressOptions { Delay = new Random().Next(20, 40)};86 await userPage.FocusAsync("input");87 await userPage.Keyboard.PressAsync("Tab", pressOptions);88 int visiblePagesCounter = pagesVisibleElements.Length;89 while (visiblePagesCounter < pagesTotalCount)90 {91 await userPage.Keyboard.PressAsync("PageDown", pressOptions);92 await Task.Delay(new Random().Next(250, 350));93 await userPage.Keyboard.PressAsync("PageDown", pressOptions);94 await Task.Delay(new Random().Next(250, 350));95 await userPage.Keyboard.PressAsync("PageDown", pressOptions);96 await Task.Delay(new Random().Next(250, 350));97 await userPage.Keyboard.PressAsync("PageDown", pressOptions);98 await Task.Delay(new Random().Next(250, 350));99 ElementHandle[] newPagesVisibleElements = await userPage.QuerySelectorAllAsync("div.fans_idol_row.inl_bl");100 if (newPagesVisibleElements.Length == visiblePagesCounter)101 {102 break;103 }104 visiblePagesCounter = newPagesVisibleElements.Length;105 }106 }107 ElementHandle[] nwPagesElements = await userPage.QuerySelectorAllAsync("div.fans_idol_info");108 foreach (var element in nwPagesElements)109 {110 VkBrwCommunity community = await GetCommunityAsync(element, userContext);111 if (community != null)112 {113 nwPages.Add(community);114 community.Users.Add(user);115 }116 }117 }118 }119 }120 ElementHandle closeButtonElement = closeBlock.First();121 await closeButtonElement.ClickAsync(clickOptions);122 }123 }124 }125 }126 else127 {128 user.HiddenProfile = true;129 ElementHandle[] pageNameElements = await userPage.QuerySelectorAllAsync("h2.page_name");130 if (pageNameElements.Length == 1)131 {132 var pageElement = pageNameElements.First();133 user.PageName = await pageElement.EvaluateFunctionAsync<string>("('h2', h2 => h2.innerText)");134 }135 }136 return nwPages;137 }138 private async Task<VkBrwCommunity> GetCommunityAsync(ElementHandle communityElement, BrowserContext userContext)139 {140 ElementHandle communityNameElement = await communityElement.QuerySelectorAsync("div.fans_idol_name");141 if (communityNameElement != null)142 {143 VkBrwCommunity nwPage = new VkBrwCommunity();144 ////await page.EvaluateFunctionAsync(@"() => {145 //// Array.from(document.querySelectorAll('li'))146 //// .find(l => l.querySelector('span').innerText === 'fire').querySelector('INPUT').click();147 ////}");148 // equals to $eval('a', a => a.innerText)149 nwPage.Name = await communityNameElement.EvaluateFunctionAsync<string>("('a', a => a.innerText)");150 ElementHandle communityLinkElement = await communityElement.QuerySelectorAsync("a.fans_idol_lnk");151 nwPage.CommunityUrl = await communityLinkElement.EvaluateFunctionAsync<string>("('a', a => a.href)");152 ElementHandle communityStatusElement = await communityElement.QuerySelectorAsync("div.fans_idol_status");153 nwPage.Status = await communityStatusElement.EvaluateFunctionAsync<string>("('div', div => div.innerText)");154 ElementHandle communitySizeElement = await communityElement.QuerySelectorAsync("div.fans_idol_size");155 nwPage.Size = await communitySizeElement.EvaluateFunctionAsync<string>("('div', div => div.innerText)");156 if (!nwPage.CommunityUrl.Contains("event"))157 {158 await GetCommunityDetailsAsync(userContext, nwPage);159 }160 return nwPage;161 }162 else163 {164 return null;165 }166 }167 private async Task GetCommunityDetailsAsync(BrowserContext browserContext, VkBrwCommunity community)168 {169 Page communityPage = await browserContext.NewPageAsync();170 ////groupPage.EvaluateFunctionAsync($"() => window.open('{groupUrl}')").GetAwaiter().GetResult();171 ////Target newWindowTarget = browser.WaitForTargetAsync(target => target.Url == "https://www.example.com/").Result;172 ////Page newPage = newWindowTarget.PageAsync().Result;173 try174 {175 await communityPage.GoToAsync(community.CommunityUrl);176 }177 catch (NavigationException)178 {179 return;180 }181 WaitForSelectorOptions waitSelectorOptions = new WaitForSelectorOptions { Timeout = 10000 };182 ElementHandle communityLoadedElement = await communityPage.WaitForSelectorAsync("div#page_wrap.scroll_fix_wrap._page_wrap", waitSelectorOptions);183 if (communityLoadedElement != null)...

Full Screen

Full Screen

BrowserContextTests.cs

Source:BrowserContextTests.cs Github

copy

Full Screen

...43 public async Task ShouldCloseAllBelongingTargetsOnceClosingContext()44 {45 Assert.Single((await Browser.PagesAsync()));46 var context = await Browser.CreateIncognitoBrowserContextAsync();47 await context.NewPageAsync();48 Assert.Equal(2, (await Browser.PagesAsync()).Length);49 Assert.Single((await context.PagesAsync()));50 await context.CloseAsync();51 Assert.Single((await Browser.PagesAsync()));52 }53 [PuppeteerTest("browsercontext.spec.ts", "BrowserContext", "window.open should use parent tab context")]54 [SkipBrowserFact(skipFirefox: true)]55 public async Task WindowOpenShouldUseParentTabContext()56 {57 var context = await Browser.CreateIncognitoBrowserContextAsync();58 var page = await context.NewPageAsync();59 await page.GoToAsync(TestConstants.EmptyPage);60 var popupTargetCompletion = new TaskCompletionSource<Target>();61 Browser.TargetCreated += (_, e) => popupTargetCompletion.SetResult(e.Target);62 await Task.WhenAll(63 popupTargetCompletion.Task,64 page.EvaluateFunctionAsync("url => window.open(url)", TestConstants.EmptyPage)65 );66 var popupTarget = await popupTargetCompletion.Task;67 Assert.Same(context, popupTarget.BrowserContext);68 await context.CloseAsync();69 }70 [PuppeteerTest("browsercontext.spec.ts", "BrowserContext", "should fire target events")]71 [SkipBrowserFact(skipFirefox: true)]72 public async Task ShouldFireTargetEvents()73 {74 var context = await Browser.CreateIncognitoBrowserContextAsync();75 var events = new List<string>();76 context.TargetCreated += (_, e) => events.Add("CREATED: " + e.Target.Url);77 context.TargetChanged += (_, e) => events.Add("CHANGED: " + e.Target.Url);78 context.TargetDestroyed += (_, e) => events.Add("DESTROYED: " + e.Target.Url);79 var page = await context.NewPageAsync();80 await page.GoToAsync(TestConstants.EmptyPage);81 await page.CloseAsync();82 Assert.Equal(new[] {83 $"CREATED: {TestConstants.AboutBlank}",84 $"CHANGED: {TestConstants.EmptyPage}",85 $"DESTROYED: {TestConstants.EmptyPage}"86 }, events);87 await context.CloseAsync();88 }89 [PuppeteerTest("browsercontext.spec.ts", "BrowserContext", "should isolate local storage and cookies")]90 [PuppeteerFact]91 public async Task ShouldIsolateLocalStorageAndCookies()92 {93 // Create two incognito contexts.94 var context1 = await Browser.CreateIncognitoBrowserContextAsync();95 var context2 = await Browser.CreateIncognitoBrowserContextAsync();96 Assert.Empty(context1.Targets());97 Assert.Empty(context2.Targets());98 // Create a page in first incognito context.99 var page1 = await context1.NewPageAsync();100 await page1.GoToAsync(TestConstants.EmptyPage);101 await page1.EvaluateExpressionAsync(@"{102 localStorage.setItem('name', 'page1');103 document.cookie = 'name=page1';104 }");105 Assert.Single(context1.Targets());106 Assert.Empty(context2.Targets());107 // Create a page in second incognito context.108 var page2 = await context2.NewPageAsync();109 await page2.GoToAsync(TestConstants.EmptyPage);110 await page2.EvaluateExpressionAsync(@"{111 localStorage.setItem('name', 'page2');112 document.cookie = 'name=page2';113 }");114 Assert.Single(context1.Targets());115 Assert.Equal(page1.Target, context1.Targets()[0]);116 Assert.Single(context2.Targets());117 Assert.Equal(page2.Target, context2.Targets()[0]);118 // Make sure pages don't share localstorage or cookies.119 Assert.Equal("page1", await page1.EvaluateExpressionAsync<string>("localStorage.getItem('name')"));120 Assert.Equal("name=page1", await page1.EvaluateExpressionAsync<string>("document.cookie"));121 Assert.Equal("page2", await page2.EvaluateExpressionAsync<string>("localStorage.getItem('name')"));122 Assert.Equal("name=page2", await page2.EvaluateExpressionAsync<string>("document.cookie"));123 // Cleanup contexts.124 await Task.WhenAll(context1.CloseAsync(), context2.CloseAsync());125 Assert.Single(Browser.BrowserContexts());126 }127 [PuppeteerTest("browsercontext.spec.ts", "BrowserContext", "should work across sessions")]128 [SkipBrowserFact(skipFirefox: true)]129 public async Task ShouldWorkAcrossSessions()130 {131 Assert.Single(Browser.BrowserContexts());132 var context = await Browser.CreateIncognitoBrowserContextAsync();133 Assert.Equal(2, Browser.BrowserContexts().Length);134 var remoteBrowser = await Puppeteer.ConnectAsync(new ConnectOptions135 {136 BrowserWSEndpoint = Browser.WebSocketEndpoint137 });138 var contexts = remoteBrowser.BrowserContexts();139 Assert.Equal(2, contexts.Length);140 remoteBrowser.Disconnect();141 await context.CloseAsync();142 }143 [PuppeteerTest("browsercontext.spec.ts", "BrowserContext", "should wait for target")]144 [SkipBrowserFact(skipFirefox: true)]145 public async Task ShouldWaitForTarget()146 {147 var context = await Browser.CreateIncognitoBrowserContextAsync();148 var targetPromise = context.WaitForTargetAsync((target) => target.Url == TestConstants.EmptyPage);149 var page = await context.NewPageAsync();150 await page.GoToAsync(TestConstants.EmptyPage);151 var promiseTarget = await targetPromise;152 var targetPage = await promiseTarget.PageAsync();153 Assert.Equal(targetPage, page);154 await context.CloseAsync();155 }156 [PuppeteerTest("browsercontext.spec.ts", "BrowserContext", "should timeout waiting for non existant target")]157 [PuppeteerFact]158 public async Task ShouldTimeoutWaitingForNonExistantTarget()159 {160 var context = await Browser.CreateIncognitoBrowserContextAsync();161 await Assert.ThrowsAsync<TimeoutException>(()162 => context.WaitForTargetAsync((target) => target.Url == TestConstants.EmptyPage, new WaitForOptions { Timeout = 1 }));163 await context.CloseAsync();...

Full Screen

Full Screen

BrowserContext.cs

Source:BrowserContext.cs Github

copy

Full Screen

...6namespace PuppeteerSharp7{8 /// <summary>9 /// BrowserContexts provide a way to operate multiple independent browser sessions. When a browser is launched, it has10 /// a single <see cref="BrowserContext"/> used by default. The method <see cref="Browser.NewPageAsync"/> creates a <see cref="Page"/> in the default <see cref="BrowserContext"/>11 /// </summary>12 public class BrowserContext13 {14 private readonly Connection _connection;15 private readonly string _id;16 internal BrowserContext(Connection connection, Browser browser, string contextId)17 {18 _connection = connection;19 Browser = browser;20 _id = contextId;21 }22 /// <summary>23 /// Raised when the url of a target changes24 /// </summary>25 public event EventHandler<TargetChangedArgs> TargetChanged;26 /// <summary>27 /// Raised when a target is created, for example when a new page is opened by <c>window.open</c> <see href="https://developer.mozilla.org/en-US/docs/Web/API/Window/open"/> or <see cref="NewPageAsync"/>.28 /// </summary>29 public event EventHandler<TargetChangedArgs> TargetCreated;30 /// <summary>31 /// Raised when a target is destroyed, for example when a page is closed32 /// </summary>33 public event EventHandler<TargetChangedArgs> TargetDestroyed;34 /// <summary>35 /// Returns whether BrowserContext is incognito36 /// The default browser context is the only non-incognito browser context37 /// </summary>38 /// <remarks>39 /// The default browser context cannot be closed40 /// </remarks>41 public bool IsIncognito => _id != null;42 /// <summary>43 /// Gets the browser this browser context belongs to44 /// </summary>45 public Browser Browser { get; }46 /// <summary>47 /// Gets an array of all active targets inside the browser context 48 /// </summary>49 /// <returns>An array of all active targets inside the browser context</returns>50 public Target[] Targets() => Array.FindAll(Browser.Targets(), target => target.BrowserContext == this);51 /// <summary>52 /// This searches for a target in this specific browser context.53 /// <example>54 /// <code>55 /// <![CDATA[56 /// await page.EvaluateAsync("() => window.open('https://www.example.com/')");57 /// var newWindowTarget = await browserContext.WaitForTargetAsync((target) => target.Url == "https://www.example.com/");58 /// ]]>59 /// </code>60 /// </example>61 /// </summary>62 /// <param name="predicate">A function to be run for every target</param>63 /// <param name="options">options</param>64 /// <returns>Resolves to the first target found that matches the predicate function.</returns>65 public Task<Target> WaitForTargetAsync(Func<Target, bool> predicate, WaitForOptions options = null)66 => Browser.WaitForTargetAsync((target) => target.BrowserContext == this && predicate(target), options);67 /// <summary>68 /// An array of all pages inside the browser context.69 /// </summary>70 /// <returns>Task which resolves to an array of all open pages. 71 /// Non visible pages, such as <c>"background_page"</c>, will not be listed here. 72 /// You can find them using <see cref="Target.PageAsync"/>.</returns>73 public async Task<Page[]> PagesAsync()74 => (await Task.WhenAll(75 Targets().Where(t => t.Type == TargetType.Page).Select(t => t.PageAsync())).ConfigureAwait(false)76 ).Where(p => p != null).ToArray();77 /// <summary>78 /// Creates a new page79 /// </summary>80 /// <returns>Task which resolves to a new <see cref="Page"/> object</returns>81 public Task<Page> NewPageAsync() => Browser.CreatePageInContextAsync(_id);82 /// <summary>83 /// Closes the browser context. All the targets that belong to the browser context will be closed84 /// </summary>85 /// <returns>Task</returns>86 public Task CloseAsync()87 {88 if (_id == null)89 {90 throw new PuppeteerException("Non-incognito profiles cannot be closed!");91 }92 return Browser.DisposeContextAsync(_id);93 }94 /// <summary>95 /// Overrides the browser context permissions....

Full Screen

Full Screen

VkBrwCommunity.cs

Source:VkBrwCommunity.cs Github

copy

Full Screen

...34 {35 Headless = false36 });37 BrowserContext userContext = await browser.CreateIncognitoBrowserContextAsync();38 Page communityPage = await userContext.NewPageAsync();39 await communityPage.SetViewportAsync(new ViewPortOptions40 {41 Height = 768,42 Width = 102443 });44 string ver = await browser.GetVersionAsync();45 string userAgent = await browser.GetUserAgentAsync();46 await communityPage.SetUserAgentAsync("Mozilla / 5.0(Windows NT 10.0; Win64; x64) AppleWebKit / 537.36(KHTML, like Gecko) Chrome / 74.0.3723.0 Safari / 537.36");47 48 await communityPage.GoToAsync(CommunityUrl);49 ElementHandle followersLoaded = await communityPage.WaitForSelectorAsync("#public_followers");50 }51 }52}...

Full Screen

Full Screen

PuppeteerPageBaseTest.cs

Source:PuppeteerPageBaseTest.cs Github

copy

Full Screen

...13 {14 Headless = true15 });16 Context = await Browser.CreateIncognitoBrowserContextAsync();17 Page = await Context.NewPageAsync();18 await SetUp();19 }20 public async Task DisposeAsync()21 {22 await TearDown();23 await Page.CloseAsync();24 await Browser.CloseAsync();25 }26 protected virtual async Task SetUp()27 {28 await Task.CompletedTask;29 }30 protected virtual async Task TearDown()31 {...

Full Screen

Full Screen

NewPageAsync

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 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);9 var browser = await Puppeteer.LaunchAsync(new LaunchOptions10 {11 });12 var context = await browser.CreateIncognitoBrowserContextAsync();13 var page = await context.NewPageAsync();14 }15 }16}17using System;18using System.Threading.Tasks;19using PuppeteerSharp;20{21 {22 static async Task Main(string[] args)23 {24 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);25 var browser = await Puppeteer.LaunchAsync(new LaunchOptions26 {27 });28 var page = await browser.NewPageAsync();29 }30 }31}32using System;33using System.Threading.Tasks;34using PuppeteerSharp;35{36 {37 static async Task Main(string[] args)38 {39 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);40 var browser = await Puppeteer.LaunchAsync(new LaunchOptions41 {42 });43 var page = await browser.NewPageAsync();44 var newPage = await page.NewPageAsync();45 }46 }47}48using System;49using System.Threading.Tasks;50using PuppeteerSharp;51{52 {53 static async Task Main(string[] args)54 {55 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);56 var browser = await Puppeteer.LaunchAsync(new LaunchOptions57 {58 });59 var page = await browser.NewPageAsync();

Full Screen

Full Screen

NewPageAsync

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 browser = await Puppeteer.LaunchAsync(new LaunchOptions9 {10 });11 var browserContext = await browser.CreateIncognitoBrowserContextAsync();12 var page = await browserContext.NewPageAsync();13 await page.ScreenshotAsync("google.png");14 await browser.CloseAsync();15 }16 }17}

Full Screen

Full Screen

NewPageAsync

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 browser = await Puppeteer.LaunchAsync(new LaunchOptions9 {10 });11 var context = await browser.CreateIncognitoBrowserContextAsync();12 var page = await context.NewPageAsync();13 await page.ScreenshotAsync("example.png");14 await browser.CloseAsync();15 }16 }17}18Related posts: PuppeteerSharp – BrowserContext.NewPageAsync() Method PuppeteerSharp – BrowserContext.Pages Property PuppeteerSharp – BrowserContext.Target Property PuppeteerSharp – BrowserContext.Targets Property PuppeteerSharp – BrowserContext.TargetsChanged Event PuppeteerSharp – BrowserContext.TargetsRemoved Event PuppeteerSharp – BrowserContext.TargetsAdded Event PuppeteerSharp – BrowserContext.Page Property PuppeteerSharp – BrowserContext.Page Event PuppeteerSharp – BrowserContext.CloseAsync() Method PuppeteerSharp – BrowserContext.SetDefaultNavigationTimeoutAsync() Method PuppeteerSharp – BrowserContext.SetDefaultTimeoutAsync() Method PuppeteerSharp – BrowserContext.SetExtraHTTPHeadersAsync() Method PuppeteerSharp – BrowserContext.SetOfflineAsync() Method PuppeteerSharp – BrowserContext.SetRequestInterceptionAsync() Method PuppeteerSharp – BrowserContext.SetUserAgentAsync() Method PuppeteerSharp – BrowserContext.SetViewportAsync() Method PuppeteerSharp

Full Screen

Full Screen

NewPageAsync

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static void Main(string[] args)7 {8 MainAsync(args).Wait();9 }10 static async Task MainAsync(string[] args)11 {12 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);13 using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false }))14 using (var page = await browser.NewPageAsync())15 {16 await Task.Delay(5000);17 }18 }19 }20}21using System;22using System.Threading.Tasks;23using PuppeteerSharp;24{25 {26 static void Main(string[] args)27 {28 MainAsync(args).Wait();29 }30 static async Task MainAsync(string[] args)31 {32 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);33 using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false }))34 using (var page = await browser.NewPageAsync())35 {36 await Task.Delay(5000);37 }38 }39 }40}41using System;42using System.Threading.Tasks;43using PuppeteerSharp;44{45 {46 static void Main(string[] args)47 {48 MainAsync(args).Wait();49 }50 static async Task MainAsync(string[] args)51 {52 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);53 using (var browser = await Puppeteer

Full Screen

Full Screen

NewPageAsync

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[] { "--no-sandbox" }10 };11 using (var browser = await Puppeteer.LaunchAsync(options))12 {13 var context = await browser.CreateIncognitoBrowserContextAsync();14 var page = await context.NewPageAsync();15 await page.ScreenshotAsync("google.png");16 }17 }18 }19}20using System;21using System.Threading.Tasks;22using PuppeteerSharp;23{24 {25 static async Task Main(string[] args)26 {27 {28 Args = new[] { "--no-sandbox" }29 };30 using (var browser = await Puppeteer.LaunchAsync(options))31 {32 var context = await browser.CreateIncognitoBrowserContextAsync();33 var page = await context.NewPageAsync();34 await page.ScreenshotAsync("google.png");35 await page.GoToAsync("

Full Screen

Full Screen

NewPageAsync

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static void Main(string[] args)7 {8 Console.WriteLine("Hello World!");9 NewPageAsyncExample obj = new NewPageAsyncExample();10 obj.NewPageAsyncDemo().Wait();11 }12 public async Task NewPageAsyncDemo()13 {14 var options = new LaunchOptions { Headless = false };15 using (var browser = await Puppeteer.LaunchAsync(options))16 using (var page = await browser.NewPageAsync())17 {

Full Screen

Full Screen

NewPageAsync

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static void Main(string[] args)7 {8 MainAsync().GetAwaiter().GetResult();9 }10 static async Task MainAsync()11 {12 var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false });13 var context = await browser.CreateIncognitoBrowserContextAsync();14 var page = await context.NewPageAsync();15 Console.ReadLine();16 }17 }18}19public Task<Page> OpenPageInNewWindowAsync(string url, bool waitForLoad = true, bool noWaitAfter = false, bool waitForNavigations = true)20using System;21using System.Threading.Tasks;22using PuppeteerSharp;23{24 {25 static void Main(string[] args)26 {27 MainAsync().GetAwaiter().GetResult();28 }

Full Screen

Full Screen

NewPageAsync

Using AI Code Generation

copy

Full Screen

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

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