Best Playwright-dotnet code snippet using Microsoft.Playwright.Core.Locator.EvaluateAsync
BotCore.cs
Source:BotCore.cs
...286 {287 if (!Headless && !_useLowCpuRam)288 try289 {290 page.EvaluateAsync("window.localStorage.setItem('video-quality', '" + itm.PreferredQuality +291 "');");292 page.ReloadAsync().GetAwaiter().GetResult();293 }294 catch (Exception)295 {296 //ignored297 }298 var matureClicked = false;299 var matureCheckCount = 0;300 var cacheClicked = false;301 var cacheCheckCount = 0;302 if (itm.LoginInfo != null)303 {304 Thread.Sleep(1000);305 var allCookies = GetCookie(itm.LoginInfo.Username);306 if (allCookies != null)307 foreach (var cookie in allCookies)308 {309 Cookie[] cookies =310 {311 new()312 {313 Domain = cookie.Domain, Expires = cookie.Expiry, Name = cookie.Name,314 Path = cookie.Path, Secure = cookie.Secure, Url = cookie.Path,315 HttpOnly = cookie.HttpOnly, Value = cookie.Value316 }317 };318 page.Context.AddCookiesAsync(cookies);319 }320 try321 {322 var loginButton =323 page.Locator(324 "xpath=/html/body/div[1]/div/div[2]/nav/div/div[3]/div[3]/div/div[1]/div[1]/button/div/div");325 if (loginButton.CountAsync().GetAwaiter().GetResult() > 0)326 {327 Click(ref loginButton);328 Thread.Sleep(1000);329 var usernameBox =330 page.Locator(331 "xpath=/html/body/div[3]/div/div/div/div/div/div[1]/div/div/div[3]/form/div/div[1]/div/div[2]/input");332 if (usernameBox.CountAsync().GetAwaiter().GetResult() > 0)333 {334 Click(ref usernameBox);335 Thread.Sleep(1000);336 usernameBox.TypeAsync(itm.LoginInfo.Username).GetAwaiter().GetResult();337 var passwordBox =338 page.Locator(339 "xpath=/html/body/div[3]/div/div/div/div/div/div[1]/div/div/div[3]/form/div/div[2]/div/div[1]/div[2]/div[1]/input");340 if (passwordBox.CountAsync().GetAwaiter().GetResult() > 0)341 {342 Click(ref passwordBox);343 Thread.Sleep(1000);344 passwordBox.TypeAsync(itm.LoginInfo.Password).GetAwaiter().GetResult();345 Thread.Sleep(1000);346 var login = page.Locator(347 "xpath=/html/body/div[3]/div/div/div/div/div/div[1]/div/div/div[3]/form/div/div[3]/button/div/div");348 Thread.Sleep(1000);349 if (login.CountAsync().GetAwaiter().GetResult() > 0)350 Click(ref login);351 }352 }353 }354 }355 catch (Exception ex)356 {357 LogMessage?.Invoke(new Exception($"Login failed: {ex.Message}"));358 }359 while (true)360 {361 Thread.Sleep(1000);362 var cookie = page.Context.CookiesAsync().GetAwaiter().GetResult()363 .Any(x => x.Name == "auth-token");364 if (cookie)365 {366 StoreCookie(new Tuple<string, List<BrowserContextCookiesResult>>(itm.LoginInfo.Username,367 new List<BrowserContextCookiesResult>(page.Context.CookiesAsync().GetAwaiter()368 .GetResult().ToArray())));369 break;370 }371 }372 }373 while (true)374 {375 try376 {377 if (_firstPage)378 {379 firstPage = true;380 _firstPage = false;381 }382 if (firstPage)383 {384 var liveViewers =385 page.Locator(386 "xpath=/html/body/div[1]/div/div[2]/div[1]/main/div[2]/div[3]/div/div/div[1]/div[1]/div[2]/div/div[1]/div/div/div/div[2]/div[2]/div[2]/div/div/div[1]/div[1]/div/p/span");387 if (liveViewers.CountAsync().GetAwaiter().GetResult() > 0)388 {389 LiveViewer.Invoke(liveViewers.InnerTextAsync().GetAwaiter().GetResult());390 Thread.Sleep(5000);391 }392 }393 }394 catch (Exception)395 {396 LiveViewer.Invoke("N/A");397 }398 Thread.Sleep(1000);399 try400 {401 var connectionError =402 page.Locator(403 "xpath=/html/body/div[1]/div/div[2]/div[1]/main/div[2]/div[3]/div/div/div[2]/div/div[2]/div/div/div/div/div[7]/div/div[3]/button/div/div[2]");404 if (connectionError.CountAsync().GetAwaiter().GetResult() > 0)405 connectionError.ClickAsync().GetAwaiter().GetResult();406 }407 catch (Exception)408 {409 //ignored410 }411 412 try413 {414 if (!matureClicked && matureCheckCount < 5)415 try416 {417 var mature =418 page.Locator(419 "xpath=/html/body/div[1]/div/div[2]/div[1]/main/div[2]/div[3]/div/div/div[2]/div/div[2]/div/div/div/div/div[5]/div/div[3]/button/div/div");420 if (mature.CountAsync().GetAwaiter().GetResult() > 0)421 {422 Click(ref mature);423 matureClicked = true;424 matureCheckCount++;425 }426 }427 catch428 {429 //ignored because there is no mature button430 }431 }432 catch (Exception)433 {434 // ignored435 }436 try437 {438 if (!cacheClicked && cacheCheckCount < 5)439 try440 {441 var cache = page.Locator(442 "xpath=/html/body/div[1]/div/div[2]/div[1]/div/div/div[3]/button/div/div/div");443 if (cache.CountAsync().GetAwaiter().GetResult() > 0)444 {445 Click(ref cache);446 cacheClicked = true;447 }448 cacheCheckCount++;449 }450 catch (Exception)451 {452 //ignored because there is no cache button453 }454 }455 catch (Exception)456 {457 // ignored458 }459 try460 {461 if (_refreshInterval != 0 &&462 DateTime.Now - startDate > TimeSpan.FromMinutes(_refreshInterval))463 {464 page.ReloadAsync().GetAwaiter().GetResult();465 startDate = DateTime.Now;466 }467 }468 catch (Exception)469 {470 //ignored471 }472 try473 {474 if (messageInterval != 0 &&475 DateTime.Now - messageStartDate > TimeSpan.FromMinutes(messageInterval) &&476 itm.LoginInfo != null)477 {478 SendMessage();479 messageStartDate = DateTime.Now;480 }481 }482 catch (Exception)483 {484 //ignored485 }486 }487 void SendMessage()488 {489 try490 {491 var chatBox = page.WaitForSelectorAsync(".chat-wysiwyg-input__editor").GetAwaiter()492 .GetResult();493 if (_chatMessages.TryTake(out var message))494 {495 chatBox?.TypeAsync(message).GetAwaiter().GetResult();496 page.Keyboard.PressAsync("Enter").GetAwaiter().GetResult();497 }498 }499 catch (Exception)500 {501 //ignored 502 }503 }504 }505 if (itm.Service == StreamService.Service.Youtube)506 {507 Thread.Sleep(3000);508 try509 {510 var play = page.Locator(511 "xpath=/html/body/ytd-app/div/ytd-page-manager/ytd-watch-flexy/div[5]/div[1]/div/div[1]/div/div/div/ytd-player/div/div/div[5]/button");512 play?.ClickAsync().GetAwaiter().GetResult();513 }514 catch (Exception)515 {516 //ignored517 }518 while (true)519 {520 try521 {522 if (_firstPage)523 {524 firstPage = true;525 _firstPage = false;526 }527 if (firstPage)528 {529 var liveViewers = page.Locator(530 "xpath=/html/body/ytd-app/div/ytd-page-manager/ytd-watch-flexy/div[5]/div[1]/div/div[6]/div[2]/ytd-video-primary-info-renderer/div/div/div[1]/div[1]/ytd-video-view-count-renderer/span[1]");531 if (liveViewers.CountAsync().GetAwaiter().GetResult() > 0)532 {533 LiveViewer.Invoke(534 liveViewers.InnerTextAsync().GetAwaiter().GetResult().Split(' ')[0]);535 Thread.Sleep(5000);536 }537 }538 }539 catch (Exception)540 {541 LiveViewer.Invoke("N/A");542 }543 try544 {545 if (_refreshInterval != 0 &&546 DateTime.Now - startDate > TimeSpan.FromMinutes(_refreshInterval))547 {548 page.ReloadAsync().GetAwaiter().GetResult();549 startDate = DateTime.Now;550 }551 }552 catch553 {554 //ignored555 }556 }557 }558 if (itm.Service == StreamService.Service.DLive)559 {560 Thread.Sleep(3000);561 var isPlaying = false;562 while (true)563 {564 try565 {566 if (_firstPage)567 {568 firstPage = true;569 _firstPage = false;570 }571 if (firstPage)572 {573 try574 {575 var liveViewers =576 page.Locator(577 "xpath=/html/body/div/div[1]/div[20]/div[2]/div/div[2]/div/div/div/div[1]/div/div[1]/div[3]/div/div[1]/div/div[2]/div[2]");578 if (liveViewers.CountAsync().GetAwaiter().GetResult() > 0)579 {580 LiveViewer.Invoke(liveViewers.InnerTextAsync().GetAwaiter().GetResult()581 .Split(" ")[0]);582 Thread.Sleep(5000);583 }584 }585 catch (Exception)586 {587 //ignored588 }589 try590 {591 var liveViewers =592 page.Locator(593 "xpath=/html/body/div/div[1]/div[18]/div[2]/div/div/div/div/div/div/div/div/div[3]/div/div[3]/div/div/div[1]/div/div[1]/div[2]/div/div[1]/span");594 if (liveViewers.CountAsync().GetAwaiter().GetResult() > 0)595 {596 LiveViewer.Invoke(liveViewers.InnerTextAsync().GetAwaiter().GetResult());597 Thread.Sleep(5000);598 }599 }600 catch (Exception)601 {602 //ignored603 }604 }605 if (!isPlaying)606 {607 var play = page.Locator(608 "xpath=/html/body/div/div[1]/div[14]/div[2]/div/div[2]/div/div/div/div/div/div/div[1]/div/div/div/div/div[4]/div[2]/button/svg");609 if (play.CountAsync().GetAwaiter().GetResult() > 0)610 {611 Click(ref play);612 isPlaying = true;613 }614 }615 Thread.Sleep(1000);616 }617 catch (Exception)618 {619 //ignored620 }621 try622 {623 if (_refreshInterval != 0 &&624 DateTime.Now - startDate > TimeSpan.FromMinutes(_refreshInterval))625 {626 page.ReloadAsync().GetAwaiter().GetResult();627 isPlaying = false;628 startDate = DateTime.Now;629 }630 }631 catch (Exception)632 {633 //ignored634 }635 }636 }637 if (itm.Service == StreamService.Service.NimoTv)638 {639 Thread.Sleep(3000);640 var isPlaying = false;641 if (itm.LoginInfo != null)642 {643 Thread.Sleep(1000);644 var allCookies = GetCookie(itm.LoginInfo.Username);645 if (allCookies != null)646 foreach (var cookie in allCookies)647 {648 Cookie[] cookies =649 {650 new()651 {652 Domain = cookie.Domain, Expires = cookie.Expiry, Name = cookie.Name,653 Path = cookie.Path, Secure = cookie.Secure, Url = cookie.Path,654 HttpOnly = cookie.HttpOnly, Value = cookie.Value655 }656 };657 page.Context.AddCookiesAsync(cookies);658 }659 try660 {661 var loginButton =662 page.Locator("xpath=/html/body/div[2]/div[1]/div/div[2]/div/div[2]/button");663 if (loginButton.CountAsync().GetAwaiter().GetResult() > 0)664 {665 Click(ref loginButton);666 Thread.Sleep(1000);667 var usernameBox =668 page.Locator(669 "xpath=/html/body/div[6]/div/div[2]/div/div[2]/div/div/div[3]/div[1]/div[2]/input");670 if (usernameBox.CountAsync().GetAwaiter().GetResult() > 0)671 {672 Click(ref usernameBox);673 Thread.Sleep(1000);674 usernameBox.TypeAsync(itm.LoginInfo.Username.Split('/')[1]).GetAwaiter()675 .GetResult();676 var countryCodeArrow =677 page.Locator(678 "xpath=/html/body/div[6]/div/div[2]/div/div[2]/div/div/div[3]/div[1]/div[2]/div[1]");679 if (countryCodeArrow.CountAsync().GetAwaiter().GetResult() > 0)680 {681 Click(ref countryCodeArrow);682 Thread.Sleep(1000);683 var searchCountryCode =684 page.Locator(685 "xpath=/html/body/div[6]/div/div[2]/div/div[4]/div/div/div/div[1]/input");686 if (searchCountryCode.CountAsync().GetAwaiter().GetResult() > 0)687 {688 searchCountryCode.TypeAsync(itm.LoginInfo.Username.Split('/')[0]689 .Replace("+", string.Empty)).GetAwaiter().GetResult();690 Thread.Sleep(1000);691 var firstElement =692 page.Locator(693 "xpath=/html/body/div[6]/div/div[2]/div/div[4]/div/div/div/div[2]/div[1]/div[2]");694 if (firstElement.CountAsync().GetAwaiter().GetResult() > 0)695 Click(ref firstElement);696 }697 }698 var passwordBox =699 page.Locator(700 "xpath=/html/body/div[6]/div/div[2]/div/div[2]/div/div/div[3]/div[1]/div[3]/input");701 if (passwordBox.CountAsync().GetAwaiter().GetResult() > 0)702 {703 Click(ref passwordBox);704 Thread.Sleep(1000);705 passwordBox.TypeAsync(itm.LoginInfo.Password).GetAwaiter().GetResult();706 Thread.Sleep(1000);707 var login = page.Locator(708 "xpath=/html/body/div[6]/div/div[2]/div/div[2]/div/div/div[3]/div[1]/button");709 Thread.Sleep(1000);710 if (login.CountAsync().GetAwaiter().GetResult() > 0)711 Click(ref login);712 }713 }714 }715 }716 catch (Exception ex)717 {718 LogMessage?.Invoke(new Exception($"Login failed: {ex.Message}"));719 }720 while (true)721 {722 Thread.Sleep(1000);723 var cookie = page.Context.CookiesAsync().GetAwaiter().GetResult()724 .Any(x => x.Name == "userName");725 if (cookie)726 {727 StoreCookie(new Tuple<string, List<BrowserContextCookiesResult>>(itm.LoginInfo.Username,728 new List<BrowserContextCookiesResult>(page.Context.CookiesAsync().GetAwaiter()729 .GetResult().ToArray())));730 break;731 }732 }733 }734 while (true)735 {736 try737 {738 if (_firstPage)739 {740 firstPage = true;741 _firstPage = false;742 }743 if (firstPage)744 {745 var liveViewers =746 page.Locator(747 "xpath=/html/body/div[2]/div[2]/div[2]/div[1]/div/div/div[2]/div[2]/div[1]/div[1]/div/div[2]/div[3]/span");748 if (liveViewers.CountAsync().GetAwaiter().GetResult() > 0)749 {750 LiveViewer.Invoke(liveViewers.InnerTextAsync().GetAwaiter().GetResult());751 Thread.Sleep(5000);752 }753 }754 }755 catch (Exception)756 {757 LiveViewer.Invoke("N/A");758 }759 try760 {761 if (!isPlaying)762 {763 var play = page.Locator(764 "xpath=/html/body/div[2]/div[2]/div[2]/div[1]/div/div/div[2]/div[2]/div[1]/div[2]/div[1]/div[2]/div/span");765 if (play.CountAsync().GetAwaiter().GetResult() > 0)766 {767 Click(ref play);768 isPlaying = true;769 }770 }771 }772 catch (Exception)773 {774 //ignored775 }776 try777 {778 if (_refreshInterval != 0 &&779 DateTime.Now - startDate > TimeSpan.FromMinutes(_refreshInterval))780 {781 page.ReloadAsync().GetAwaiter().GetResult();782 isPlaying = false;783 startDate = DateTime.Now;784 }785 }786 catch (Exception)787 {788 //ignored789 }790 try791 {792 if (messageInterval != 0 &&793 DateTime.Now - messageStartDate > TimeSpan.FromMinutes(messageInterval) &&794 itm.LoginInfo != null)795 {796 SendMessage();797 messageStartDate = DateTime.Now;798 }799 }800 catch (Exception)801 {802 //ignored803 }804 void SendMessage()805 {806 try807 {808 var chatBox = page.WaitForSelectorAsync(".nimo-room__chatroom__chat-box__input")809 .GetAwaiter().GetResult();810 if (chatBox != null && _chatMessages.TryTake(out var message))811 {812 chatBox.TypeAsync(message).GetAwaiter().GetResult();813 page.Keyboard.PressAsync("Enter");814 }815 }816 catch (Exception)817 {818 //ignored 819 }820 }821 Thread.Sleep(1000);822 }823 }824 if (itm.Service == StreamService.Service.Twitter)825 {826 Thread.Sleep(3000);827 while (true)828 {829 try830 {831 if (_firstPage)832 {833 firstPage = true;834 _firstPage = false;835 }836 if (firstPage)837 {838 var liveViewers =839 page.Locator(840 "xpath=/html/body/div[2]/div[2]/div[2]/div[1]/div/div/div[2]/div[2]/div[1]/div[1]/div/div[2]/div[3]/span");841 if (liveViewers.CountAsync().GetAwaiter().GetResult() > 0)842 {843 LiveViewer.Invoke(liveViewers.InnerTextAsync().GetAwaiter().GetResult());844 Thread.Sleep(5000);845 }846 }847 }848 catch (Exception)849 {850 LiveViewer.Invoke("N/A");851 }852 try853 {854 if (_refreshInterval != 0 &&855 DateTime.Now - startDate > TimeSpan.FromMinutes(_refreshInterval))856 {857 page.ReloadAsync().GetAwaiter().GetResult();858 startDate = DateTime.Now;859 }860 }861 catch (Exception)862 {863 //ignored864 }865 Thread.Sleep(1000);866 }867 }868 if (itm.Service == StreamService.Service.Facebook)869 {870 Thread.Sleep(3000);871 if (itm.LoginInfo != null)872 {873 Thread.Sleep(1000);874 var allCookies = GetCookie(itm.LoginInfo.Username);875 if (allCookies != null)876 foreach (var cookie in allCookies)877 {878 Cookie[] cookies =879 {880 new()881 {882 Domain = cookie.Domain, Expires = cookie.Expiry, Name = cookie.Name,883 Path = cookie.Path, Secure = cookie.Secure, Url = cookie.Path,884 HttpOnly = cookie.HttpOnly, Value = cookie.Value885 }886 };887 page.Context.AddCookiesAsync(cookies);888 }889 try890 {891 var usernameBox =892 page.Locator(893 "xpath=/html/body/div[1]/div/div[1]/div/div[2]/div[2]/div[2]/div/form/div[2]/div[1]/label/input");894 if (usernameBox.CountAsync().GetAwaiter().GetResult() > 0)895 {896 Click(ref usernameBox);897 Thread.Sleep(1000);898 usernameBox.TypeAsync(itm.LoginInfo.Username).GetAwaiter().GetResult();899 var passwordBox =900 page.Locator(901 "xpath=/html/body/div[1]/div/div[1]/div/div[2]/div[2]/div[2]/div/form/div[2]/div[2]/label/input");902 if (passwordBox.CountAsync().GetAwaiter().GetResult() > 0)903 {904 Click(ref passwordBox);905 Thread.Sleep(1000);906 passwordBox.TypeAsync(itm.LoginInfo.Password).GetAwaiter().GetResult();907 Thread.Sleep(1000);908 var login = page.Locator(909 "xpath=/html/body/div[1]/div/div[1]/div/div[2]/div[2]/div[2]/div/form/div[2]/div[3]/div/div/div[1]/div/span/span");910 Thread.Sleep(1000);911 if (login.CountAsync().GetAwaiter().GetResult() > 0)912 Click(ref login);913 }914 }915 }916 catch (Exception ex)917 {918 LogMessage?.Invoke(new Exception($"Login failed: {ex.Message}"));919 }920 Thread.Sleep(3000);921 page.ReloadAsync().GetAwaiter().GetResult();922 while (true)923 {924 Thread.Sleep(1000);925 var cookie = page.Context.CookiesAsync().GetAwaiter().GetResult()926 .Any(x => x.Name == "c_user");927 if (cookie)928 {929 StoreCookie(new Tuple<string, List<BrowserContextCookiesResult>>(itm.LoginInfo.Username,930 new List<BrowserContextCookiesResult>(page.Context.CookiesAsync().GetAwaiter()931 .GetResult().ToArray())));932 break;933 }934 }935 }936 while (true)937 {938 try939 {940 if (_firstPage)941 {942 firstPage = true;943 _firstPage = false;944 }945 if (firstPage)946 {947 var liveViewers =948 page.Locator(949 "xpath=/html/body/div[1]/div/div[1]/div/div[3]/div/div/div[1]/div[2]/div[1]/div/div/div/div[1]/div[1]/div/div/div/div[2]/div/div[5]/div[2]/span[2]");950 if (liveViewers.CountAsync().GetAwaiter().GetResult() > 0)951 {952 LiveViewer.Invoke(liveViewers.InnerTextAsync().GetAwaiter().GetResult());953 Thread.Sleep(5000);954 }955 }956 }957 catch (Exception)958 {959 //ignored960 }961 try962 {963 if (_refreshInterval != 0 &&964 DateTime.Now - startDate > TimeSpan.FromMinutes(_refreshInterval))965 {966 page.ReloadAsync().GetAwaiter().GetResult();967 startDate = DateTime.Now;968 }969 }970 catch (Exception)971 {972 //ignored973 }974 }975 }976 if (itm.Service == StreamService.Service.TrovoLive)977 {978 Thread.Sleep(5000);979 if (!Headless && !_useLowCpuRam)980 try981 {982 page.EvaluateAsync("window.localStorage.setItem('live/userClarityLevel', '" +983 itm.PreferredQuality + "');");984 page.ReloadAsync().GetAwaiter().GetResult();985 }986 catch (Exception)987 {988 //ignored989 }990 if (itm.LoginInfo != null)991 {992 Thread.Sleep(1000);993 var allCookies = GetCookie(itm.LoginInfo.Username);994 if (allCookies != null)995 foreach (var cookie in allCookies)996 {...
Page.cs
Source:Page.cs
...360 {361 // Swallow exception362 }363 }364 public Task<T> EvaluateAsync<T>(string expression, object arg) => MainFrame.EvaluateAsync<T>(expression, arg);365 public Task<JsonElement?> EvalOnSelectorAsync(string selector, string expression, object arg) => MainFrame.EvalOnSelectorAsync(selector, expression, arg);366 public Task<T> EvalOnSelectorAsync<T>(string selector, string expression, object arg = null, PageEvalOnSelectorOptions options = null)367 => MainFrame.EvalOnSelectorAsync<T>(selector, expression, arg, new() { Strict = options?.Strict });368 public ILocator Locator(string selector, PageLocatorOptions options = default)369 => MainFrame.Locator(selector, new() { HasTextString = options?.HasTextString, HasTextRegex = options?.HasTextRegex, Has = options?.Has });370 public Task<IElementHandle> QuerySelectorAsync(string selector, PageQuerySelectorOptions options = null)371 => MainFrame.QuerySelectorAsync(selector, new() { Strict = options?.Strict });372 public Task<T> EvalOnSelectorAsync<T>(string selector, string expression, object arg) => MainFrame.EvalOnSelectorAsync<T>(selector, expression, arg);373 public Task<JsonElement?> EvalOnSelectorAllAsync(string selector, string expression, object arg) => MainFrame.EvalOnSelectorAllAsync(selector, expression, arg);374 public Task<T> EvalOnSelectorAllAsync<T>(string selector, string expression, object arg) => MainFrame.EvalOnSelectorAllAsync<T>(selector, expression, arg);375 public Task FillAsync(string selector, string value, PageFillOptions options = default)376 => MainFrame.FillAsync(selector, value, new() { NoWaitAfter = options?.NoWaitAfter, Timeout = options?.Timeout, Force = options?.Force, Strict = options?.Strict });377 public Task SetInputFilesAsync(string selector, string files, PageSetInputFilesOptions options = default)378 => MainFrame.SetInputFilesAsync(selector, files, Map(options));379 public Task SetInputFilesAsync(string selector, IEnumerable<string> files, PageSetInputFilesOptions options = default)380 => MainFrame.SetInputFilesAsync(selector, files, Map(options));381 public Task SetInputFilesAsync(string selector, FilePayload files, PageSetInputFilesOptions options = default)382 => MainFrame.SetInputFilesAsync(selector, files, Map(options));383 public Task SetInputFilesAsync(string selector, IEnumerable<FilePayload> files, PageSetInputFilesOptions options = default)384 => MainFrame.SetInputFilesAsync(selector, files, Map(options));385 public Task TypeAsync(string selector, string text, PageTypeOptions options = default)386 => MainFrame.TypeAsync(selector, text, new()387 {388 Delay = options?.Delay,389 NoWaitAfter = options?.NoWaitAfter,390 Timeout = options?.Timeout,391 Strict = options?.Strict,392 });393 public Task FocusAsync(string selector, PageFocusOptions options = default)394 => MainFrame.FocusAsync(selector, new()395 {396 Timeout = options?.Timeout,397 Strict = options?.Strict,398 });399 public Task HoverAsync(string selector, PageHoverOptions options = default)400 => MainFrame.HoverAsync(401 selector,402 new()403 {404 Position = options?.Position,405 Modifiers = options?.Modifiers,406 Force = options?.Force,407 Timeout = options?.Timeout,408 Trial = options?.Trial,409 Strict = options?.Strict,410 });411 public Task PressAsync(string selector, string key, PagePressOptions options = default)412 => MainFrame.PressAsync(selector, key, new()413 {414 Delay = options?.Delay,415 NoWaitAfter = options?.NoWaitAfter,416 Timeout = options?.Timeout,417 Strict = options?.Strict,418 });419 public Task<IReadOnlyList<string>> SelectOptionAsync(string selector, string values, PageSelectOptionOptions options = default)420 => SelectOptionAsync(selector, new[] { values }, options);421 public Task<IReadOnlyList<string>> SelectOptionAsync(string selector, IEnumerable<string> values, PageSelectOptionOptions options = default)422 => SelectOptionAsync(selector, values.Select(x => new SelectOptionValue() { Value = x }), options);423 public Task<IReadOnlyList<string>> SelectOptionAsync(string selector, IElementHandle values, PageSelectOptionOptions options = default)424 => SelectOptionAsync(selector, new[] { values }, options);425 public Task<IReadOnlyList<string>> SelectOptionAsync(string selector, IEnumerable<IElementHandle> values, PageSelectOptionOptions options = default)426 => MainFrame.SelectOptionAsync(selector, values, new()427 {428 NoWaitAfter = options?.NoWaitAfter,429 Timeout = options?.Timeout,430 Force = options?.Force,431 Strict = options?.Strict,432 });433 public Task<IReadOnlyList<string>> SelectOptionAsync(string selector, SelectOptionValue values, PageSelectOptionOptions options = default)434 => SelectOptionAsync(selector, new[] { values }, options);435 public Task<IReadOnlyList<string>> SelectOptionAsync(string selector, IEnumerable<SelectOptionValue> values, PageSelectOptionOptions options = default)436 => MainFrame.SelectOptionAsync(selector, values, new()437 {438 NoWaitAfter = options?.NoWaitAfter,439 Timeout = options?.Timeout,440 Force = options?.Force,441 Strict = options?.Strict,442 });443 public Task WaitForTimeoutAsync(float timeout) => MainFrame.WaitForTimeoutAsync(timeout);444 public Task<IElementHandle> WaitForSelectorAsync(string selector, PageWaitForSelectorOptions options = default)445 => MainFrame.WaitForSelectorAsync(selector, new()446 {447 State = options?.State,448 Timeout = options?.Timeout,449 Strict = options?.Strict,450 });451 public Task<JsonElement?> EvaluateAsync(string expression, object arg) => MainFrame.EvaluateAsync(expression, arg);452 public async Task<byte[]> ScreenshotAsync(PageScreenshotOptions options = default)453 {454 options ??= new PageScreenshotOptions();455 if (options.Type == null && !string.IsNullOrEmpty(options.Path))456 {457 options.Type = ElementHandle.DetermineScreenshotType(options.Path);458 }459 byte[] result = await _channel.ScreenshotAsync(460 path: options.Path,461 fullPage: options.FullPage,462 clip: options.Clip,463 omitBackground: options.OmitBackground,464 type: options.Type,465 quality: options.Quality,...
Frame.cs
Source:Frame.cs
...409 public async Task<IJSHandle> EvaluateHandleAsync(string script, object args = null)410 => (await _channel.EvaluateExpressionHandleAsync(411 script,412 arg: ScriptsHelper.SerializedArgument(args)).ConfigureAwait(false))?.Object;413 public async Task<JsonElement?> EvaluateAsync(string script, object arg = null)414 => ScriptsHelper.ParseEvaluateResult<JsonElement?>(await _channel.EvaluateExpressionAsync(415 script,416 arg: ScriptsHelper.SerializedArgument(arg)).ConfigureAwait(false));417 public async Task<T> EvaluateAsync<T>(string script, object arg = null)418 => ScriptsHelper.ParseEvaluateResult<T>(await _channel.EvaluateExpressionAsync(419 script,420 arg: ScriptsHelper.SerializedArgument(arg)).ConfigureAwait(false));421 public async Task<JsonElement?> EvalOnSelectorAsync(string selector, string script, object arg = null)422 => ScriptsHelper.ParseEvaluateResult<JsonElement?>(await _channel.EvalOnSelectorAsync(423 selector: selector,424 script,425 arg: ScriptsHelper.SerializedArgument(arg),426 strict: null).ConfigureAwait(false));427 public async Task<T> EvalOnSelectorAsync<T>(string selector, string script, object arg = null)428 => ScriptsHelper.ParseEvaluateResult<T>(await _channel.EvalOnSelectorAsync(429 selector: selector,430 script,431 arg: ScriptsHelper.SerializedArgument(arg),...
BrowserTypeConnectTests.cs
Source:BrowserTypeConnectTests.cs
...56 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);57 var browserContext = await browser.NewContextAsync();58 Assert.AreEqual(browserContext.Pages.Count, 0);59 var page = await browserContext.NewPageAsync();60 Assert.AreEqual(await page.EvaluateAsync<int>("11 * 11"), 121);61 await page.GotoAsync(Server.EmptyPage);62 await browser.CloseAsync();63 }64 {65 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);66 var browserContext = await browser.NewContextAsync();67 var page = await browserContext.NewPageAsync();68 await page.GotoAsync(Server.EmptyPage);69 await browser.CloseAsync();70 }71 }72 [PlaywrightTest("browsertype-connect.spec.ts", "should send default User-Agent and X-Playwright-Browser headers with connect request")]73 public async Task ShouldSendDefaultUserAgentAndPlaywrightBrowserHeadersWithConnectRequest()74 {75 var connectionRequest = Server.WaitForWebSocketConnectionRequest();76 BrowserType.ConnectAsync($"ws://localhost:{Server.Port}/ws", new()77 {78 Headers = new Dictionary<string, string>()79 {80 ["hello-foo"] = "i-am-bar",81 }82 }).IgnoreException();83 var request = await connectionRequest;84 StringAssert.Contains("Playwright", request.Headers["User-Agent"]);85 Assert.AreEqual(request.Headers["hello-foo"], "i-am-bar");86 Assert.AreEqual(request.Headers["x-playwright-browser"], BrowserType.Name);87 }88 [PlaywrightTest("browsertype-connect.spec.ts", "should be able to connect two browsers at the same time")]89 public async Task ShouldBeAbleToConnectTwoBrowsersAtTheSameTime()90 {91 var browser1 = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);92 Assert.AreEqual(browser1.Contexts.Count, 0);93 await browser1.NewContextAsync();94 Assert.AreEqual(browser1.Contexts.Count, 1);95 var browser2 = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);96 Assert.AreEqual(browser2.Contexts.Count, 0);97 await browser2.NewContextAsync();98 Assert.AreEqual(browser2.Contexts.Count, 1);99 Assert.AreEqual(browser1.Contexts.Count, 1);100 await browser1.CloseAsync();101 Assert.AreEqual(browser2.Contexts.Count, 1);102 var page2 = await browser2.NewPageAsync();103 Assert.AreEqual(await page2.EvaluateAsync<int>("7 * 6"), 42); // original browser should still work104 await browser2.CloseAsync();105 }106 [PlaywrightTest("browsertype-connect.spec.ts", "should timeout in connect while connecting")]107 [Skip(SkipAttribute.Targets.Windows)]108 public async Task ShouldTimeoutInConnectWhileConnecting()109 {110 var exception = await PlaywrightAssert.ThrowsAsync<TimeoutException>(async () => await BrowserType.ConnectAsync($"ws://localhost:{Server.Port}/ws", new BrowserTypeConnectOptions { Timeout = 100 }));111 StringAssert.Contains("BrowserType.ConnectAsync: Timeout 100ms exceeded", exception.Message);112 }113 [PlaywrightTest("browsertype-connect.spec.ts", "should support slowmo option")]114 public async Task ShouldSupportSlowMo()115 {116 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint, new BrowserTypeConnectOptions { SlowMo = 200 });117 var start = DateTime.Now;118 var context = await browser.NewContextAsync();119 await browser.CloseAsync();120 Assert.Greater((DateTime.Now - start).TotalMilliseconds, 199);121 }122 [PlaywrightTest("browsertype-connect.spec.ts", "disconnected event should be emitted when browser is closed or server is closed")]123 public async Task DisconnectedEventShouldBeEmittedWhenBrowserIsClosedOrServerIsClosed()124 {125 var browser1 = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);126 await browser1.NewPageAsync();127 var browser2 = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);128 await browser2.NewPageAsync();129 int disconnected1 = 0;130 int disconnected2 = 0;131 browser1.Disconnected += (_, e) => disconnected1++;132 browser2.Disconnected += (_, e) => disconnected2++;133 var tsc1 = new TaskCompletionSource<object>();134 browser1.Disconnected += (_, e) => tsc1.SetResult(null);135 await browser1.CloseAsync();136 await tsc1.Task;137 Assert.AreEqual(disconnected1, 1);138 Assert.AreEqual(disconnected2, 0);139 var tsc2 = new TaskCompletionSource<object>();140 browser2.Disconnected += (_, e) => tsc2.SetResult(null);141 await browser2.CloseAsync();142 await tsc2.Task;143 Assert.AreEqual(disconnected1, 1);144 Assert.AreEqual(disconnected2, 1);145 }146 [PlaywrightTest("browsertype-connect.spec.ts", "disconnected event should have browser as argument")]147 public async Task DisconnectedEventShouldHaveBrowserAsArguments()148 {149 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);150 IBrowser disconneced = null;151 var tsc = new TaskCompletionSource<object>();152 browser.Disconnected += (_, browser) =>153 {154 disconneced = browser;155 tsc.SetResult(null);156 };157 await browser.CloseAsync();158 await tsc.Task;159 Assert.AreEqual(browser, disconneced);160 }161 [PlaywrightTest("browsertype-connect.spec.ts", "should set the browser connected state")]162 public async Task ShouldSetTheBrowserConnectedState()163 {164 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);165 Assert.AreEqual(browser.IsConnected, true);166 var tsc = new TaskCompletionSource<bool>();167 browser.Disconnected += (_, e) => tsc.SetResult(false);168 _remoteServer.Close();169 await tsc.Task;170 Assert.AreEqual(browser.IsConnected, false);171 }172 [PlaywrightTest("browsertype-connect.spec.ts", "should throw when used after isConnected returns false")]173 public async Task ShouldThrowWhenUsedAfterIsConnectedReturnsFalse()174 {175 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);176 var page = await browser.NewPageAsync();177 var tsc = new TaskCompletionSource<bool>();178 browser.Disconnected += (_, e) => tsc.SetResult(false);179 _remoteServer.Close();180 await tsc.Task;181 Assert.AreEqual(browser.IsConnected, false);182 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(async () => await page.EvaluateAsync("1 + 1"));183 StringAssert.Contains("has been closed", exception.Message);184 }185 [PlaywrightTest("browsertype-connect.spec.ts", "should throw when calling waitForNavigation after disconnect")]186 public async Task ShouldThrowWhenWhenCallingWaitForNavigationAfterDisconnect()187 {188 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);189 var page = await browser.NewPageAsync();190 var tsc = new TaskCompletionSource<bool>();191 browser.Disconnected += (_, e) => tsc.SetResult(false);192 _remoteServer.Close();193 await tsc.Task;194 Assert.AreEqual(browser.IsConnected, false);195 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(async () => await page.WaitForNavigationAsync());196 StringAssert.Contains("Navigation failed because page was closed", exception.Message);197 }198 [PlaywrightTest("browsertype-connect.spec.ts", "should reject navigation when browser closes")]199 public async Task ShouldRejectNavigationWhenBrowserCloses()200 {201 Server.SetRoute("/one-style.css", context =>202 {203 context.Response.Redirect("/one-style.css");204 return Task.CompletedTask;205 });206 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);207 var page = await browser.NewPageAsync();208 var PageGoto = page.GotoAsync(Server.Prefix + "/one-style.html", new PageGotoOptions { Timeout = 60000 });209 await Server.WaitForRequest("/one-style.css");210 await browser.CloseAsync();211 Assert.AreEqual(browser.IsConnected, false);212 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(async () => await PageGoto);213 StringAssert.Contains("has been closed", exception.Message);214 }215 [PlaywrightTest("browsertype-connect.spec.ts", "should reject waitForSelector when browser closes")]216 public async Task ShouldRejectWaitForSelectorWhenBrowserCloses()217 {218 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);219 var page = await browser.NewPageAsync();220 var watchdog = page.WaitForSelectorAsync("div");221 await browser.CloseAsync();222 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(async () => await watchdog);223 Assert.That(exception.Message, Contains.Substring("has been closed"));224 }225 [PlaywrightTest("browsertype-connect.spec.ts", "should emit close events on pages and contexts")]226 public async Task ShouldEmitCloseEventsOnPagesAndContexts()227 {228 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);229 var context = await browser.NewContextAsync();230 var tsc = new TaskCompletionSource<object>();231 context.Close += (_, e) => tsc.SetResult(null);232 var page = await context.NewPageAsync();233 bool pageClosed = false;234 page.Close += (_, e) => pageClosed = true;235 _remoteServer.Close();236 await tsc.Task;237 Assert.AreEqual(pageClosed, true);238 }239 [PlaywrightTest("browsertype-connect.spec.ts", "should terminate network waiters")]240 public async Task ShouldTerminateNetworkWaiters()241 {242 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);243 var page = await browser.NewPageAsync();244 var requestWatchdog = page.WaitForRequestAsync(Server.EmptyPage);245 var responseWatchog = page.WaitForResponseAsync(Server.EmptyPage);246 _remoteServer.Close();247 async Task CheckTaskHasException(Task task)248 {249 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(async () => await task);250 StringAssert.Contains("Page closed", exception.Message);251 StringAssert.DoesNotContain("Timeout", exception.Message);252 }253 await CheckTaskHasException(requestWatchdog);254 await CheckTaskHasException(responseWatchog);255 }256 [PlaywrightTest("browsertype-connect.spec.ts", "should not throw on close after disconnect")]257 public async Task ShouldNotThrowOnCloseAfterDisconnect()258 {259 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);260 var page = await browser.NewPageAsync();261 var tcs = new TaskCompletionSource<bool>();262 browser.Disconnected += (_, e) => tcs.SetResult(true);263 _remoteServer.Close();264 await tcs.Task;265 await browser.CloseAsync();266 }267 [PlaywrightTest("browsertype-connect.spec.ts", "should not throw on context.close after disconnect")]268 public async Task ShouldNotThrowOnContextCloseAfterDisconnect()269 {270 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);271 var context = await browser.NewContextAsync();272 await context.NewPageAsync();273 var tcs = new TaskCompletionSource<bool>();274 browser.Disconnected += (_, e) => tcs.SetResult(true);275 _remoteServer.Close();276 await tcs.Task;277 await context.CloseAsync();278 }279 [PlaywrightTest("browsertype-connect.spec.ts", "should not throw on page.close after disconnect")]280 public async Task ShouldNotThrowOnPageCloseAfterDisconnect()281 {282 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);283 var context = await browser.NewContextAsync();284 var page = await context.NewPageAsync();285 var tcs = new TaskCompletionSource<bool>();286 browser.Disconnected += (_, e) => tcs.SetResult(true);287 _remoteServer.Close();288 await tcs.Task;289 await page.CloseAsync();290 }291 [PlaywrightTest("browsertype-connect.spec.ts", "should saveAs videos from remote browser")]292 public async Task ShouldSaveAsVideosFromRemoteBrowser()293 {294 using var tempDirectory = new TempDirectory();295 var videoPath = tempDirectory.Path;296 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);297 var context = await browser.NewContextAsync(new()298 {299 RecordVideoDir = videoPath,300 RecordVideoSize = new() { Height = 320, Width = 240 }301 });302 var page = await context.NewPageAsync();303 await page.EvaluateAsync("() => document.body.style.backgroundColor = 'red'");304 await Task.Delay(1000);305 await context.CloseAsync();306 var videoSavePath = tempDirectory.Path + "my-video.webm";307 await page.Video.SaveAsAsync(videoSavePath);308 Assert.That(videoSavePath, Does.Exist);309 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(async () => await page.Video.PathAsync());310 StringAssert.Contains("Path is not available when connecting remotely. Use SaveAsAsync() to save a local copy", exception.Message);311 }312 [PlaywrightTest("browsertype-connect.spec.ts", "should save download")]313 public async Task ShouldSaveDownload()314 {315 Server.SetRoute("/download", context =>316 {317 context.Response.Headers["Content-Type"] = "application/octet-stream";318 context.Response.Headers["Content-Disposition"] = "attachment";319 return context.Response.WriteAsync("Hello world");320 });321 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);322 var page = await browser.NewPageAsync(new() { AcceptDownloads = true });323 await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");324 var downloadTask = page.WaitForDownloadAsync();325 await TaskUtils.WhenAll(326 downloadTask,327 page.ClickAsync("a"));328 using var tmpDir = new TempDirectory();329 string userPath = Path.Combine(tmpDir.Path, "these", "are", "directories", "download.txt");330 var download = downloadTask.Result;331 await download.SaveAsAsync(userPath);332 Assert.True(new FileInfo(userPath).Exists);333 Assert.AreEqual("Hello world", File.ReadAllText(userPath));334 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => download.PathAsync());335 Assert.AreEqual("Path is not available when connecting remotely. Use SaveAsAsync() to save a local copy.", exception.Message);336 await browser.CloseAsync();337 }338 [PlaywrightTest("browsertype-connect.spec.ts", "should error when saving download after deletion")]339 public async Task ShouldErrorWhenSavingDownloadAfterDeletion()340 {341 Server.SetRoute("/download", context =>342 {343 context.Response.Headers["Content-Type"] = "application/octet-stream";344 context.Response.Headers["Content-Disposition"] = "attachment";345 return context.Response.WriteAsync("Hello world");346 });347 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);348 var page = await browser.NewPageAsync(new() { AcceptDownloads = true });349 await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");350 var downloadTask = page.WaitForDownloadAsync();351 await TaskUtils.WhenAll(352 downloadTask,353 page.ClickAsync("a"));354 using var tmpDir = new TempDirectory();355 string userPath = Path.Combine(tmpDir.Path, "download.txt");356 var download = downloadTask.Result;357 await download.DeleteAsync();358 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => download.SaveAsAsync(userPath));359 StringAssert.Contains("Target page, context or browser has been closed", exception.Message);360 await browser.CloseAsync();361 }362 [PlaywrightTest("browsertype-connect.spec.ts", "should save har")]363 public async Task ShouldSaveHar()364 {365 using var tempDirectory = new TempDirectory();366 var harPath = tempDirectory.Path + "/test.har";367 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);368 var context = await browser.NewContextAsync(new()369 {370 RecordHarPath = harPath371 });372 var page = await context.NewPageAsync();373 await page.GotoAsync(Server.EmptyPage);374 await context.CloseAsync();375 await browser.CloseAsync();376 Assert.That(harPath, Does.Exist);377 var logString = System.IO.File.ReadAllText(harPath);378 StringAssert.Contains(Server.EmptyPage, logString);379 }380 [PlaywrightTest("browsertype-connect.spec.ts", "should record trace with sources")]381 public async Task ShouldRecordContextTraces()382 {383 using var tempDirectory = new TempDirectory();384 var tracePath = tempDirectory.Path + "/trace.zip";385 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);386 var context = await browser.NewContextAsync();387 var page = await context.NewPageAsync();388 await context.Tracing.StartAsync(new() { Sources = true });389 await page.GotoAsync(Server.EmptyPage);390 await page.SetContentAsync("<button>Click</button>");391 await page.ClickAsync("button");392 await context.Tracing.StopAsync(new TracingStopOptions { Path = tracePath });393 await browser.CloseAsync();394 Assert.That(tracePath, Does.Exist);395 ZipFile.ExtractToDirectory(tracePath, tempDirectory.Path);396 Assert.That(tempDirectory.Path + "/trace.trace", Does.Exist);397 Assert.That(tempDirectory.Path + "/trace.network", Does.Exist);398 Assert.AreEqual(1, Directory.GetFiles(Path.Join(tempDirectory.Path, "resources"), "*.txt").Length);399 }400 [PlaywrightTest("browsertype-connect.spec.ts", "should upload large file")]401 [Skip(SkipAttribute.Targets.Firefox, SkipAttribute.Targets.Webkit)]402 public async Task ShouldUploadLargeFile()403 {404 var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);405 var context = await browser.NewContextAsync();406 var page = await context.NewPageAsync();407 await page.GotoAsync(Server.Prefix + "/input/fileupload.html");408 using var tmpDir = new TempDirectory();409 var filePath = Path.Combine(tmpDir.Path, "200MB");410 using (var stream = File.OpenWrite(filePath))411 {412 var str = new string('a', 4 * 1024);413 for (var i = 0; i < 50 * 1024; i++)414 {415 await stream.WriteAsync(Encoding.UTF8.GetBytes(str));416 }417 }418 var input = page.Locator("input[type=file]");419 var events = await input.EvaluateHandleAsync(@"e => {420 const events = [];421 e.addEventListener('input', () => events.push('input'));422 e.addEventListener('change', () => events.push('change'));423 return events;424 }");425 await input.SetInputFilesAsync(filePath);426 Assert.AreEqual(await input.EvaluateAsync<string>("e => e.files[0].name"), "200MB");427 Assert.AreEqual(await events.EvaluateAsync<string[]>("e => e"), new[] { "input", "change" });428 var (file0Name, file0Size) = await TaskUtils.WhenAll(429 Server.WaitForRequest("/upload", request => (request.Form.Files[0].FileName, request.Form.Files[0].Length)),430 page.ClickAsync("input[type=submit]")431 );432 Assert.AreEqual("200MB", file0Name);433 Assert.AreEqual(200 * 1024 * 1024, file0Size);434 }435 private class RemoteServer436 {437 private Process Process { get; set; }438 public string WSEndpoint { get; set; }439 internal RemoteServer(string browserName)440 {441 try...
Locator.cs
Source:Locator.cs
...111 public Task<IReadOnlyList<IElementHandle>> ElementHandlesAsync()112 => _frame.QuerySelectorAllAsync(_selector);113 public Task<T> EvaluateAllAsync<T>(string expression, object arg = null)114 => _frame.EvalOnSelectorAllAsync<T>(_selector, expression, arg);115 public Task<JsonElement?> EvaluateAsync(string expression, object arg = null, LocatorEvaluateOptions options = null)116 => EvaluateAsync<JsonElement?>(expression, arg, options);117 public Task<T> EvaluateAsync<T>(string expression, object arg = null, LocatorEvaluateOptions options = null)118 => _frame.EvalOnSelectorAsync<T>(_selector, expression, arg, ConvertOptions<FrameEvalOnSelectorOptions>(options));119 public async Task<IJSHandle> EvaluateHandleAsync(string expression, object arg = null, LocatorEvaluateHandleOptions options = null)120 => await WithElementAsync(async (e, _) => await e.EvaluateHandleAsync(expression, arg).ConfigureAwait(false), options).ConfigureAwait(false);121 public async Task FillAsync(string value, LocatorFillOptions options = null)122 => await _frame.FillAsync(_selector, value, ConvertOptions<FrameFillOptions>(options)).ConfigureAwait(false);123 public Task FocusAsync(LocatorFocusOptions options = null)124 => _frame.FocusAsync(_selector, ConvertOptions<FrameFocusOptions>(options));125 IFrameLocator ILocator.FrameLocator(string selector) =>126 new FrameLocator(_frame, $"{_selector} >> {selector}");127 public Task<string> GetAttributeAsync(string name, LocatorGetAttributeOptions options = null)128 => _frame.GetAttributeAsync(_selector, name, ConvertOptions<FrameGetAttributeOptions>(options));129 public Task HoverAsync(LocatorHoverOptions options = null)130 => _frame.HoverAsync(_selector, ConvertOptions<FrameHoverOptions>(options));131 public Task<string> InnerHTMLAsync(LocatorInnerHTMLOptions options = null)...
PlaywrightIPhoneTest.cs
Source:PlaywrightIPhoneTest.cs
...40 }41 await browser.CloseAsync();42 }43 public static async Task MarkTestStatus(string status, string reason, IPage page) {44 await page.EvaluateAsync("_ => {}", "browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\":\"" + status + "\", \"reason\": \"" + reason + "\"}}");45 }46}...
PlaywrightPixelTest.cs
Source:PlaywrightPixelTest.cs
...40 }41 await browser.CloseAsync();42 }43 public static async Task MarkTestStatus(string status, string reason, IPage page) {44 await page.EvaluateAsync("_ => {}", "browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\":\"" + status + "\", \"reason\": \"" + reason + "\"}}");45 }46}...
EvaluateAsync
Using AI Code Generation
1var playwright = await Playwright.CreateAsync();2var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions3{4});5var context = await browser.NewContextAsync();6var page = await context.NewPageAsync();7var element = await page.QuerySelectorAsync("input#sb_form_q");8await element.TypeAsync("playwright");9await page.ClickAsync("input#sb_form_go");10var result = await element.EvaluateAsync<string>("e => e.value");11Console.WriteLine(result);12await browser.CloseAsync();13var playwright = await Playwright.CreateAsync();14var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions15{16});17var context = await browser.NewContextAsync();18var page = await context.NewPageAsync();19var element = await page.QuerySelectorAsync("input#sb_form_q");20await element.TypeAsync("playwright");21await page.ClickAsync("input#sb_form_go");22var result = await element.EvaluateAsync<string>("e => e.value");23Console.WriteLine(result);24await browser.CloseAsync();25var playwright = await Playwright.CreateAsync();26var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions27{28});29var context = await browser.NewContextAsync();30var page = await context.NewPageAsync();31var element = await page.QuerySelectorAsync("input#sb_form_q");32await element.TypeAsync("playwright");33await page.ClickAsync("input#sb_form_go");34var result = await element.EvaluateAsync<string>("e => e.value");35Console.WriteLine(result);36await browser.CloseAsync();37var playwright = await Playwright.CreateAsync();38var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions39{40});41var context = await browser.NewContextAsync();42var page = await context.NewPageAsync();
EvaluateAsync
Using AI Code Generation
1using Microsoft.Playwright;2using System;3using System.Threading.Tasks;4{5 {6 static async Task Main(string[] args)7 {8 using var playwright = await Playwright.CreateAsync();9 await using var browser = await playwright.Chromium.LaunchAsync();10 var page = await browser.NewPageAsync();11 var element = await page.QuerySelectorAsync("input[name='q']");12 var value = await element.EvaluateAsync<string>("element => element.value");13 Console.WriteLine(value);14 }15 }16}
EvaluateAsync
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using Microsoft.Playwright;4{5 {6 static async Task Main(string[] args)7 {8 await using var playwright = await Playwright.CreateAsync();9 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions10 {11 });12 var page = await browser.NewPageAsync();13 await page.ClickAsync("text=Sign in");14 await page.TypeAsync("input[name='identifier']", "
EvaluateAsync
Using AI Code Generation
1using Microsoft.Playwright;2using System.Threading.Tasks;3{4 {5 static async Task Main(string[] args)6 {7 using var playwright = await Playwright.CreateAsync();8 await using var browser = await playwright.Chromium.LaunchAsync();9 var page = await browser.NewPageAsync();10 var element = await page.QuerySelectorAsync("input[name='q']");11 var value = await element.EvaluateAsync("element => element.value");12 System.Console.WriteLine(value);13 }14 }15}16using Microsoft.Playwright;17using System.Threading.Tasks;18{19 {20 static async Task Main(string[] args)21 {22 using var playwright = await Playwright.CreateAsync();23 await using var browser = await playwright.Chromium.LaunchAsync();24 var page = await browser.NewPageAsync();25 var element = await page.QuerySelectorAsync("input[name='q']");26 var value = await element.EvaluateAsync("element => element.value");27 System.Console.WriteLine(value);28 }29 }30}31using Microsoft.Playwright;32using System.Threading.Tasks;33{34 {35 static async Task Main(string[] args)36 {37 using var playwright = await Playwright.CreateAsync();38 await using var browser = await playwright.Chromium.LaunchAsync();39 var page = await browser.NewPageAsync();40 var element = await page.QuerySelectorAsync("input[name='q']");41 var value = await element.EvaluateAsync("element => element.value");42 System.Console.WriteLine(value);43 }44 }45}46using Microsoft.Playwright;47using System.Threading.Tasks;
EvaluateAsync
Using AI Code Generation
1var playwright = await Playwright.CreateAsync();2var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions {3});4var context = await browser.NewContextAsync();5var page = await context.NewPageAsync();6await page.FillAsync("input[aria-label='Search']", "playwright");7await page.PressAsync("input[aria-label='Search']", "Enter");8await page.WaitForLoadStateAsync();9var locator = page.Locator("text=Playwright");10var elementHandle = await locator.FirstAsync();11var text = await elementHandle.EvaluateAsync<string>("e => e.innerText");12Console.WriteLine(text);13await browser.CloseAsync();14var playwright = await Playwright.CreateAsync();15var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions {16});17var context = await browser.NewContextAsync();18var page = await context.NewPageAsync();19await page.FillAsync("input[aria-label='Search']", "playwright");20await page.PressAsync("input[aria-label='Search']", "Enter");21await page.WaitForLoadStateAsync();22var locator = page.Locator("text=Playwright");23var elementHandle = await locator.FirstAsync();24var text = await elementHandle.EvaluateAsync<string>("e => e.innerText");25Console.WriteLine(text);26await browser.CloseAsync();27var playwright = await Playwright.CreateAsync();28var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions {29});30var context = await browser.NewContextAsync();31var page = await context.NewPageAsync();
EvaluateAsync
Using AI Code Generation
1var playwright = await Playwright.CreateAsync();2var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions {3});4var context = await browser.NewContextAsync();5var page = await context.NewPageAsync();6await page.FillAsync("input[aria-label='Search']", "playwright");7await page.PressAsync("input[aria-label='Search']", "Enter");8await page.WaitForLoadStateAsync();9var locator = page.Locator("text=Playwright");10var elementHandle = await locator.FirstAsync();11var text = await elementHandle.EvaluateAsync<string>("e => e.innerText");12Console.WriteLine(text);13await browser.CloseAsync();14var playwright = await Playwright.CreateAsync();15var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions {16});17var context = await browser.NewContextAsync();18var page = await context.NewPageAsync();19await page.FillAsync("input[aria-label='Search']", "playwright");20await page.PressAsync("input[aria-label='Search']", "Enter");
EvaluateAsync
Using AI Code Generation
1using System;2using System.Collections.Generic;3using System.Linq;4using System.Text;5using System.Threading.Tasks;6using Microsoft.Playwright;7{8 {9 static async Task Main(string[] args)10 {11 using var playwright = await Playwright.CreateAsync();12 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions13 {14 });15 var page = await browser.NewPageAsync();16 await page.WaitForLoadStateAsync(LoadState.DOMContentLoaded);17 await page.TypeAsync("input[name='q']", "playwright");18 await page.ClickAsync("input[value='Google Search']");19 await page.WaitForLoadStateAsync(LoadState.DOMContentLoaded);20 var results = await page.Locator("div.g").EvaluateAsync<List<string>>("div>div:first-child>a>h3");21 foreach (var result in results)22 {23 Console.WriteLine(result);24 }25 }26 }27}28using System;29using System.Collections.Generic;30using System.Linq;31using System.Text;32using System.Threading.Tasks;33using Microsoft.Playwright;34{35 {36 static async Task Main(string[] args)37 {38 using var playwright = await Playwright.CreateAsync();39await page.WaitForLoadStateAsync();40var locator = page.Locator("text=Playwright");41var elementHandle = await locator.FirstAsync();42var text = await elementHandle.EvaluateAsync<string>("e => e.innerText");43Console.WriteLine(text);44await browser.CloseAsync();45var playwright = await Playwright.CreateAsync();46var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions {47});48var context = await browser.NewContextAsync();49var page = await context.NewPageAsync();
EvaluateAsync
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using Microsoft.Playwright;4using Microsoft.Playwright.Core;5using Microsoft.Playwright.Transport.Channels;6{7 {8 static async Task Main(string[] args)9 {10 using var playwright = await Playwright.CreateAsync();11 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions12 {13 });14 var page = await browser.NewPageAsync();15 await page.TypeAsync("input[name=q]", "Playwright");16 await page.ClickAsync("input[name=btnK]");17 var locator = page.Locator("span:has-text(\"Microsoft Playwright\")");18 var element = await locator.EvaluateAsync<LocatorChannel>("(element) => element");19 Console.WriteLine("Element is: " + element);20 }21 }22}
EvaluateAsync
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using Microsoft.Playwright;4using Microsoft.Playwright.Core;5using Microsoft.Playwright.Transport.Channels;6{7 {8 static async Task Main(string[] args)9 {10 using var playwright = await Playwright.CreateAsync();11 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions12 {13 });14 var page = await browser.NewPageAsync();15 await page.TypeAsync("input[name=q]", "Playwright");16 await page.ClickAsync("input[name=btnK]");17 var locator = page.Locator("span:has-text(\"Microsoft Playwright\")");18 var element = await locator.EvaluateAsync<LocatorChannel>("(element) => element");19 Console.WriteLine("Element is: " + element);20 }21 }22}
EvaluateAsync
Using AI Code Generation
1using Microsoft.Playwright;2using System;3using System.Threading.Tasks;4{5 {6 static async Task Main(string[] args)7 {8 using var playwright = await Playwright.CreateAsync();9 await using var browser = await playwright.Chromium.LaunchAsync(new()10 {11 });12 var context = await browser.NewContextAsync();13 var page = await context.NewPageAsync();14 await page.EvaluateAsync("() => document.querySelector('input[name=q]').value = 'Hello World!'");15 await page.ClickAsync("input[name=q]");16 await page.Keyboard.PressAsync("Enter");17 Console.WriteLine("Hello World!");18 Console.ReadLine();19 }20 }21}
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!