How to use Locator method of Microsoft.Playwright.Core.Locator class

Best Playwright-dotnet code snippet using Microsoft.Playwright.Core.Locator.Locator

BotCore.cs

Source:BotCore.cs Github

copy

Full Screen

...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 {997 Cookie[] cookies =998 {999 new()1000 {1001 Domain = cookie.Domain, Expires = cookie.Expiry, Name = cookie.Name,1002 Path = cookie.Path, Secure = cookie.Secure, Url = cookie.Path,1003 HttpOnly = cookie.HttpOnly, Value = cookie.Value1004 }1005 };1006 page.Context.AddCookiesAsync(cookies);1007 }1008 try1009 {1010 var loginSignUpButton =1011 page.Locator("xpath=/html/body/div[1]/div/div/nav/div[3]/div[3]/button");1012 if (loginSignUpButton.CountAsync().GetAwaiter().GetResult() > 0)1013 {1014 Click(ref loginSignUpButton);1015 Thread.Sleep(4000);1016 ILocator usernameBox;1017 try1018 {1019 usernameBox =1020 page.Locator(1021 "xpath=/html/body/div[4]/div/div[2]/div[3]/div[1]/div[1]/div/input");1022 }1023 catch1024 {1025 usernameBox =1026 page.Locator(1027 "xpath=/html/body/div[4]/div/div[2]/div[3]/div[1]/div[1]/div[1]/input");1028 }1029 if (usernameBox.CountAsync().GetAwaiter().GetResult() > 0)1030 {1031 Click(ref usernameBox);1032 Thread.Sleep(1000);1033 usernameBox.TypeAsync(itm.LoginInfo.Username).GetAwaiter().GetResult();1034 Thread.Sleep(1000);1035 var passwordBox =1036 page.Locator(1037 "xpath=/html/body/div[4]/div/div[2]/div[3]/div[1]/div[3]/div/input");1038 if (passwordBox.CountAsync().GetAwaiter().GetResult() > 0)1039 {1040 passwordBox.TypeAsync(itm.LoginInfo.Password).GetAwaiter().GetResult();1041 var login = page.Locator(1042 "xpath=/html/body/div[4]/div/div[2]/div[3]/div[1]/button");1043 Thread.Sleep(1000);1044 if (login.CountAsync().GetAwaiter().GetResult() > 0)1045 Click(ref login);1046 }1047 }1048 }1049 }1050 catch (Exception ex)1051 {1052 LogMessage?.Invoke(new Exception($"Login failed: {ex.Message}"));1053 }1054 Thread.Sleep(3000);1055 page.ReloadAsync().GetAwaiter().GetResult();1056 while (true)1057 {1058 Thread.Sleep(1000);1059 var cookie = page.Context.CookiesAsync().GetAwaiter().GetResult().Any(x => x.Name == "uid");1060 if (cookie)1061 {1062 StoreCookie(new Tuple<string, List<BrowserContextCookiesResult>>(itm.LoginInfo.Username,1063 new List<BrowserContextCookiesResult>(page.Context.CookiesAsync().GetAwaiter()1064 .GetResult().ToArray())));1065 break;1066 }1067 }1068 }1069 var matureClicked = false;1070 var chatRulesClicked = false;1071 var matureCheckCount = 0;1072 while (true)1073 {1074 try1075 {1076 if (_firstPage)1077 {1078 firstPage = true;1079 _firstPage = false;1080 }1081 if (firstPage)1082 {1083 var liveViewers =1084 page.Locator(1085 "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]");1086 if (liveViewers.CountAsync().GetAwaiter().GetResult() > 0)1087 {1088 LiveViewer.Invoke(liveViewers.InnerTextAsync().GetAwaiter().GetResult());1089 Thread.Sleep(5000);1090 }1091 }1092 }1093 catch (Exception)1094 {1095 //ignored1096 }1097 try1098 {1099 if (_refreshInterval != 0 &&1100 DateTime.Now - startDate > TimeSpan.FromMinutes(_refreshInterval))1101 {1102 page.ReloadAsync().GetAwaiter().GetResult();1103 startDate = DateTime.Now;1104 }1105 }1106 catch (Exception)1107 {1108 //ignored1109 }1110 try1111 {1112 if (!matureClicked && matureCheckCount < 5)1113 try1114 {1115 ILocator mature = null;1116 try1117 {1118 mature = page.Locator(1119 "xpath=/html/body/div[1]/div/div/div/div[2]/div/div/div[1]/div[1]/div[1]/div/div[4]/div[3]/section/div/button[2]");1120 }1121 catch1122 {1123 //ignored1124 }1125 if (mature.CountAsync().GetAwaiter().GetResult() == 0)1126 mature = page.Locator(1127 "xpath=/html/body/div[1]/div/div/div/div[2]/div/div/div[1]/div[1]/div[1]/div/div[2]/div[3]/section/div/button[2]");1128 if (mature.CountAsync().GetAwaiter().GetResult() > 0)1129 {1130 Click(ref mature);1131 matureClicked = true;1132 }1133 matureCheckCount++;1134 }1135 catch1136 {1137 //ignored because there is no mature button1138 }1139 }1140 catch (Exception)1141 {1142 // ignored1143 }1144 if (!chatRulesClicked)1145 try1146 {1147 var chatRules = page.Locator(1148 "xpath=/html/body/div[1]/div/div/div/div[2]/div/section/div[3]/div/section/section/div/button");1149 if (chatRules.CountAsync().GetAwaiter().GetResult() > 0)1150 {1151 chatRules.ClickAsync().GetAwaiter().GetResult();1152 chatRulesClicked = true;1153 }1154 }1155 catch (Exception)1156 {1157 //ignored1158 }1159 try1160 {1161 if (messageInterval != 0 &&1162 DateTime.Now - messageStartDate > TimeSpan.FromMinutes(messageInterval) &&1163 itm.LoginInfo != null)1164 {1165 SendMessage();1166 messageStartDate = DateTime.Now;1167 }1168 }1169 catch (Exception)1170 {1171 //ignored1172 }1173 void SendMessage()1174 {1175 try1176 {1177 var chatBox =1178 page.Locator(1179 "xpath=/html/body/div[1]/div/div/div/div[2]/div/section/div[3]/div/section/div[1]/div[1]/div[1]");1180 if (chatBox.CountAsync().GetAwaiter().GetResult() > 0 &&1181 _chatMessages.TryTake(out var message))1182 {1183 chatBox.TypeAsync(message).GetAwaiter().GetResult();1184 page.Keyboard.PressAsync("Enter");1185 }1186 }1187 catch (Exception)1188 {1189 //ignored 1190 }1191 }1192 Thread.Sleep(1000);1193 }1194 }1195 if (itm.Service == StreamService.Service.BigoLive)1196 {1197 Thread.Sleep(2000);1198 page.ReloadAsync().GetAwaiter().GetResult();1199 1200 /*if (itm.LoginInfo != null)1201 {1202 Thread.Sleep(1000);1203 var allCookies = GetCookie(itm.LoginInfo.Username);1204 if (allCookies != null)1205 foreach (var cookie in allCookies)1206 {1207 Cookie[] cookies =1208 {1209 new()1210 {1211 Domain = cookie.Domain, Expires = cookie.Expiry, Name = cookie.Name,1212 Path = cookie.Path, Secure = cookie.Secure, Url = cookie.Path,1213 HttpOnly = cookie.HttpOnly, Value = cookie.Value1214 }1215 };1216 page.Context.AddCookiesAsync(cookies);1217 }1218 try1219 {1220 var loginSignUpButton =1221 page.Locator("xpath=/html/body/div/div/div/header/div[2]/div/button");1222 if (loginSignUpButton.CountAsync().GetAwaiter().GetResult() > 0)1223 {1224 Click(ref loginSignUpButton);1225 1226 var withCredentialsButton =1227 page.Locator("xpath=/html/body/div/div[2]/div/header/div[3]/div/div[2]");1228 if (withCredentialsButton.CountAsync().GetAwaiter().GetResult() > 0)1229 {1230 Click(ref withCredentialsButton);1231 Thread.Sleep(4000);1232 ILocator usernameBox;1233 try1234 {1235 usernameBox =1236 page.Locator(1237 "xpath=/html/body/div[4]/div/div[2]/div[3]/div[1]/div[1]/div/input");1238 }1239 catch1240 {1241 usernameBox =1242 page.Locator(1243 "xpath=/html/body/div[4]/div/div[2]/div[3]/div[1]/div[1]/div[1]/input");1244 }1245 if (usernameBox.CountAsync().GetAwaiter().GetResult() > 0)1246 {1247 Click(ref usernameBox);1248 Thread.Sleep(1000);1249 usernameBox.TypeAsync(itm.LoginInfo.Username).GetAwaiter().GetResult();1250 Thread.Sleep(1000);1251 var passwordBox =1252 page.Locator(1253 "xpath=/html/body/div[4]/div/div[2]/div[3]/div[1]/div[3]/div/input");1254 if (passwordBox.CountAsync().GetAwaiter().GetResult() > 0)1255 {1256 passwordBox.TypeAsync(itm.LoginInfo.Password).GetAwaiter().GetResult();1257 var login = page.Locator(1258 "xpath=/html/body/div[4]/div/div[2]/div[3]/div[1]/button");1259 Thread.Sleep(1000);1260 if (login.CountAsync().GetAwaiter().GetResult() > 0)1261 Click(ref login);1262 }1263 }1264 }1265 }1266 }1267 catch (Exception ex)1268 {1269 LogMessage?.Invoke(new Exception($"Login failed: {ex.Message}"));1270 }1271 Thread.Sleep(3000);1272 page.ReloadAsync().GetAwaiter().GetResult();1273 while (true)1274 {1275 Thread.Sleep(1000);1276 var cookie = page.Context.CookiesAsync().GetAwaiter().GetResult().Any(x => x.Name == "uid");1277 if (cookie)1278 {1279 StoreCookie(new Tuple<string, List<BrowserContextCookiesResult>>(itm.LoginInfo.Username,1280 new List<BrowserContextCookiesResult>(page.Context.CookiesAsync().GetAwaiter()1281 .GetResult().ToArray())));1282 break;1283 }1284 }1285 }*/1286 while (true)1287 {1288 try1289 {1290 if (_firstPage)1291 {1292 firstPage = true;1293 _firstPage = false;1294 }1295 if (firstPage)1296 {1297 var liveViewers = page.WaitForSelectorAsync(".info-view-nums").GetAwaiter().GetResult();1298 1299 if (liveViewers != null)1300 {1301 LiveViewer.Invoke(liveViewers.InnerTextAsync().GetAwaiter().GetResult());1302 Thread.Sleep(5000);1303 }1304 }1305 }1306 catch (Exception)1307 {1308 //ignored1309 }1310 try1311 {1312 if (_refreshInterval != 0 &&1313 DateTime.Now - startDate > TimeSpan.FromMinutes(_refreshInterval))1314 {1315 page.ReloadAsync().GetAwaiter().GetResult();1316 startDate = DateTime.Now;1317 }1318 }1319 catch (Exception)1320 {1321 //ignored1322 }1323 Thread.Sleep(1000);1324 }1325 }1326 try1327 {1328 page.CloseAsync().GetAwaiter().GetResult();1329 }1330 catch (Exception)1331 {1332 //ignored1333 }1334 }1335 catch (InvalidOperationException ex)1336 {1337 if (ex.Message.Contains("only supports Chrome version"))1338 {1339 CanRun = false;1340 InitializationError?.Invoke(new Exception("Please update your Google Chrome!"));1341 }1342 }1343 catch (Exception ex)1344 {1345 InitializationError?.Invoke(ex);1346 }1347 }1348 private void Click(ref ILocator locator)1349 {1350 locator.ClickAsync().GetAwaiter().GetResult();1351 }1352 private class MyCookie1353 {1354 public bool Secure { get; set; }1355 public bool HttpOnly { get; set; }1356 public string Name { get; set; }1357 public string Value { get; set; }1358 public string Domain { get; set; }1359 public string Path { get; set; }1360 public float Expiry { get; set; }1361 }1362}...

Full Screen

Full Screen

Frame.cs

Source:Frame.cs Github

copy

Full Screen

...92 public bool IsDetached { get; internal set; }93 internal List<Frame> ChildFramesList { get; } = new();94 public async Task<IElementHandle> FrameElementAsync()95 => (await _channel.FrameElementAsync().ConfigureAwait(false)).Object;96 public IFrameLocator FrameLocator(string selector)97 => new FrameLocator(this, selector);98 public Task<string> TitleAsync() => _channel.TitleAsync();99 public Task WaitForTimeoutAsync(float timeout)100 => _channel.WaitForTimeoutAsync(timeout);101 public Task<IReadOnlyList<string>> SelectOptionAsync(string selector, string values, FrameSelectOptionOptions options = default)102 => SelectOptionAsync(selector, new[] { values }, options);103 public Task<IReadOnlyList<string>> SelectOptionAsync(string selector, IEnumerable<string> values, FrameSelectOptionOptions options = default)104 => SelectOptionAsync(selector, values.Select(x => new SelectOptionValue() { Value = x }), options);105 public Task<IReadOnlyList<string>> SelectOptionAsync(string selector, IElementHandle values, FrameSelectOptionOptions options = default)106 => SelectOptionAsync(selector, new[] { values }, options);107 public async Task<IReadOnlyList<string>> SelectOptionAsync(string selector, IEnumerable<IElementHandle> values, FrameSelectOptionOptions options = default)108 => (await _channel.SelectOptionAsync(109 selector,110 values.Select(x => x as ElementHandle),111 noWaitAfter: options?.NoWaitAfter,112 strict: options?.Strict,113 force: options?.Force,114 timeout: options?.Timeout).ConfigureAwait(false)).ToList().AsReadOnly();115 public Task<IReadOnlyList<string>> SelectOptionAsync(string selector, SelectOptionValue values, FrameSelectOptionOptions options = default)116 => SelectOptionAsync(selector, new[] { values }, options);117 public async Task<IReadOnlyList<string>> SelectOptionAsync(string selector, IEnumerable<SelectOptionValue> values, FrameSelectOptionOptions options = default)118 => (await _channel.SelectOptionAsync(119 selector,120 values,121 noWaitAfter: options?.NoWaitAfter,122 strict: options?.Strict,123 force: options?.Force,124 timeout: options?.Timeout).ConfigureAwait(false)).ToList().AsReadOnly();125 public async Task WaitForLoadStateAsync(LoadState? state = default, FrameWaitForLoadStateOptions options = default)126 {127 Task<WaitUntilState> task;128 Waiter waiter = null;129 WaitUntilState loadState = Microsoft.Playwright.WaitUntilState.Load;130 switch (state)131 {132 case Microsoft.Playwright.LoadState.Load:133 loadState = Microsoft.Playwright.WaitUntilState.Load;134 break;135 case Microsoft.Playwright.LoadState.DOMContentLoaded:136 loadState = Microsoft.Playwright.WaitUntilState.DOMContentLoaded;137 break;138 case Microsoft.Playwright.LoadState.NetworkIdle:139 loadState = Microsoft.Playwright.WaitUntilState.NetworkIdle;140 break;141 }142 try143 {144 lock (_loadStates)145 {146 if (_loadStates.Contains(loadState))147 {148 return;149 }150 waiter = SetupNavigationWaiter("frame.WaitForLoadStateAsync", options?.Timeout);151 task = waiter.WaitForEventAsync<WaitUntilState>(this, "LoadState", s =>152 {153 waiter.Log($" \"{s}\" event fired");154 return s == loadState;155 });156 }157 await task.ConfigureAwait(false);158 }159 finally160 {161 waiter?.Dispose();162 }163 }164 public async Task<IResponse> WaitForNavigationAsync(FrameWaitForNavigationOptions options = default)165 {166 WaitUntilState waitUntil2 = options?.WaitUntil ?? WaitUntilState.Load;167 using var waiter = SetupNavigationWaiter("frame.WaitForNavigationAsync", options?.Timeout);168 string toUrl = !string.IsNullOrEmpty(options?.UrlString) ? $" to \"{options?.UrlString}\"" : string.Empty;169 waiter.Log($"waiting for navigation{toUrl} until \"{waitUntil2}\"");170 var navigatedEventTask = waiter.WaitForEventAsync<FrameNavigatedEventArgs>(171 this,172 "Navigated",173 e =>174 {175 // Any failed navigation results in a rejection.176 if (e.Error != null)177 {178 return true;179 }180 waiter.Log($" navigated to \"{e.Url}\"");181 return UrlMatches(e.Url, options?.UrlString, options?.UrlRegex, options?.UrlFunc);182 });183 var navigatedEvent = await navigatedEventTask.ConfigureAwait(false);184 if (navigatedEvent.Error != null)185 {186 var ex = new PlaywrightException(navigatedEvent.Error);187 await waiter.WaitForPromiseAsync(Task.FromException<object>(ex)).ConfigureAwait(false);188 }189 if (!_loadStates.Select(s => s.ToValueString()).Contains(waitUntil2.ToValueString()))190 {191 await waiter.WaitForEventAsync<WaitUntilState>(192 this,193 "LoadState",194 e =>195 {196 waiter.Log($" \"{e}\" event fired");197 return e.ToValueString() == waitUntil2.ToValueString();198 }).ConfigureAwait(false);199 }200 var request = navigatedEvent.NewDocument?.Request?.Object;201 var response = request != null202 ? await waiter.WaitForPromiseAsync(request.FinalRequest.ResponseAsync()).ConfigureAwait(false)203 : null;204 return response;205 }206 public async Task<IResponse> RunAndWaitForNavigationAsync(Func<Task> action, FrameRunAndWaitForNavigationOptions options = default)207 {208 var result = WaitForNavigationAsync(new()209 {210 UrlString = options?.UrlString,211 UrlRegex = options?.UrlRegex,212 UrlFunc = options?.UrlFunc,213 WaitUntil = options?.WaitUntil,214 Timeout = options?.Timeout,215 });216 if (action != null)217 {218 await WrapApiBoundaryAsync(() => Task.WhenAll(result, action())).ConfigureAwait(false);219 }220 return await result.ConfigureAwait(false);221 }222 public Task TapAsync(string selector, FrameTapOptions options = default)223 => _channel.TapAsync(224 selector,225 modifiers: options?.Modifiers,226 position: options?.Position,227 timeout: options?.Timeout,228 force: options?.Force,229 noWaitAfter: options?.NoWaitAfter,230 trial: options?.Trial,231 strict: options?.Strict);232 internal Task<int> QueryCountAsync(string selector)233 => _channel.QueryCountAsync(selector);234 public Task<string> ContentAsync() => _channel.ContentAsync();235 public Task FocusAsync(string selector, FrameFocusOptions options = default)236 => _channel.FocusAsync(selector, options?.Timeout, options?.Strict);237 public Task TypeAsync(string selector, string text, FrameTypeOptions options = default)238 => _channel.TypeAsync(239 selector,240 text,241 delay: options?.Delay,242 timeout: options?.Timeout,243 noWaitAfter: options?.NoWaitAfter,244 strict: options?.Strict);245 public Task<string> GetAttributeAsync(string selector, string name, FrameGetAttributeOptions options = default)246 => _channel.GetAttributeAsync(selector, name, options?.Timeout, options?.Strict);247 public Task<string> InnerHTMLAsync(string selector, FrameInnerHTMLOptions options = default)248 => _channel.InnerHTMLAsync(selector, options?.Timeout, options?.Strict);249 public Task<string> InnerTextAsync(string selector, FrameInnerTextOptions options = default)250 => _channel.InnerTextAsync(selector, options?.Timeout, options?.Strict);251 public Task<string> TextContentAsync(string selector, FrameTextContentOptions options = default)252 => _channel.TextContentAsync(selector, options?.Timeout, options?.Strict);253 public Task HoverAsync(string selector, FrameHoverOptions options = default)254 => _channel.HoverAsync(255 selector,256 position: options?.Position,257 modifiers: options?.Modifiers,258 force: options?.Force,259 timeout: options?.Timeout,260 trial: options?.Trial,261 strict: options?.Strict);262 public Task PressAsync(string selector, string key, FramePressOptions options = default)263 => _channel.PressAsync(264 selector,265 key,266 delay: options?.Delay,267 timeout: options?.Timeout,268 noWaitAfter: options?.NoWaitAfter,269 strict: options?.Strict);270 public Task DispatchEventAsync(string selector, string type, object eventInit = default, FrameDispatchEventOptions options = default)271 => _channel.DispatchEventAsync(272 selector,273 type,274 ScriptsHelper.SerializedArgument(eventInit),275 options?.Timeout,276 options?.Strict);277 public Task FillAsync(string selector, string value, FrameFillOptions options = default)278 => _channel.FillAsync(selector, value, force: options?.Force, timeout: options?.Timeout, noWaitAfter: options?.NoWaitAfter, options?.Strict);279 public async Task<IElementHandle> AddScriptTagAsync(FrameAddScriptTagOptions options = default)280 {281 var content = options?.Content;282 if (!string.IsNullOrEmpty(options?.Path))283 {284 content = File.ReadAllText(options.Path);285 content += "//# sourceURL=" + options.Path.Replace("\n", string.Empty);286 }287 return (await _channel.AddScriptTagAsync(options?.Url, options?.Path, content, options?.Type).ConfigureAwait(false)).Object;288 }289 public async Task<IElementHandle> AddStyleTagAsync(FrameAddStyleTagOptions options = default)290 {291 var content = options?.Content;292 if (!string.IsNullOrEmpty(options?.Path))293 {294 content = File.ReadAllText(options.Path);295 content += "//# sourceURL=" + options.Path.Replace("\n", string.Empty);296 }297 return (await _channel.AddStyleTagAsync(options?.Url, options?.Path, content).ConfigureAwait(false)).Object;298 }299 public Task SetInputFilesAsync(string selector, string files, FrameSetInputFilesOptions options = default)300 => SetInputFilesAsync(selector, new[] { files }, options);301 public async Task SetInputFilesAsync(string selector, IEnumerable<string> files, FrameSetInputFilesOptions options = default)302 {303 var converted = await SetInputFilesHelpers.ConvertInputFilesAsync(files, (BrowserContext)Page.Context).ConfigureAwait(false);304 if (converted.Files != null)305 {306 await _channel.SetInputFilesAsync(selector, converted.Files, options?.NoWaitAfter, options?.Timeout, options?.Strict).ConfigureAwait(false);307 }308 else309 {310 await _channel.SetInputFilePathsAsync(selector, converted?.LocalPaths, converted?.Streams, options?.NoWaitAfter, options?.Timeout, options?.Strict).ConfigureAwait(false);311 }312 }313 public Task SetInputFilesAsync(string selector, FilePayload files, FrameSetInputFilesOptions options = default)314 => SetInputFilesAsync(selector, new[] { files }, options);315 public async Task SetInputFilesAsync(string selector, IEnumerable<FilePayload> files, FrameSetInputFilesOptions options = default)316 {317 var converted = SetInputFilesHelpers.ConvertInputFiles(files);318 await _channel.SetInputFilesAsync(selector, converted.Files, noWaitAfter: options?.NoWaitAfter, timeout: options?.Timeout, options?.Strict).ConfigureAwait(false);319 }320 public Task ClickAsync(string selector, FrameClickOptions options = default)321 => _channel.ClickAsync(322 selector,323 delay: options?.Delay,324 button: options?.Button,325 clickCount: options?.ClickCount,326 modifiers: options?.Modifiers,327 position: options?.Position,328 timeout: options?.Timeout,329 force: options?.Force,330 noWaitAfter: options?.NoWaitAfter,331 trial: options?.Trial,332 strict: options?.Strict);333 public Task DblClickAsync(string selector, FrameDblClickOptions options = default)334 => _channel.DblClickAsync(335 selector,336 delay: options?.Delay,337 button: options?.Button,338 position: options?.Position,339 modifiers: options?.Modifiers,340 timeout: options?.Timeout,341 force: options?.Force,342 noWaitAfter: options?.NoWaitAfter,343 trial: options?.Trial,344 strict: options?.Strict);345 public Task CheckAsync(string selector, FrameCheckOptions options = default)346 => _channel.CheckAsync(347 selector,348 position: options?.Position,349 timeout: options?.Timeout,350 force: options?.Force,351 noWaitAfter: options?.NoWaitAfter,352 trial: options?.Trial,353 strict: options?.Strict);354 public Task UncheckAsync(string selector, FrameUncheckOptions options = default)355 => _channel.UncheckAsync(356 selector,357 position: options?.Position,358 timeout: options?.Timeout,359 force: options?.Force,360 noWaitAfter: options?.NoWaitAfter,361 trial: options?.Trial,362 strict: options?.Strict);363 public Task SetCheckedAsync(string selector, bool checkedState, FrameSetCheckedOptions options = null)364 => checkedState ?365 _channel.CheckAsync(366 selector,367 position: options?.Position,368 timeout: options?.Timeout,369 force: options?.Force,370 noWaitAfter: options?.NoWaitAfter,371 trial: options?.Trial,372 strict: options?.Strict)373 : _channel.UncheckAsync(374 selector,375 position: options?.Position,376 timeout: options?.Timeout,377 force: options?.Force,378 noWaitAfter: options?.NoWaitAfter,379 trial: options?.Trial,380 strict: options?.Strict);381 public Task SetContentAsync(string html, FrameSetContentOptions options = default)382 => _channel.SetContentAsync(html, timeout: options?.Timeout, waitUntil: options?.WaitUntil);383 public Task<string> InputValueAsync(string selector, FrameInputValueOptions options = null)384 => _channel.InputValueAsync(selector, options?.Timeout, options?.Strict);385 public async Task<IElementHandle> QuerySelectorAsync(string selector)386 => (await _channel.QuerySelectorAsync(selector).ConfigureAwait(false))?.Object;387 public async Task<IReadOnlyList<IElementHandle>> QuerySelectorAllAsync(string selector)388 => (await _channel.QuerySelectorAllAsync(selector).ConfigureAwait(false)).Select(c => ((ElementHandleChannel)c).Object).ToList().AsReadOnly();389 public async Task<IJSHandle> WaitForFunctionAsync(string expression, object arg = default, FrameWaitForFunctionOptions options = default)390 => (await _channel.WaitForFunctionAsync(391 expression: expression,392 arg: ScriptsHelper.SerializedArgument(arg),393 timeout: options?.Timeout,394 polling: options?.PollingInterval).ConfigureAwait(false)).Object;395 public async Task<IElementHandle> WaitForSelectorAsync(string selector, FrameWaitForSelectorOptions options = default)396 => (await _channel.WaitForSelectorAsync(397 selector: selector,398 state: options?.State,399 timeout: options?.Timeout,400 strict: options?.Strict,401 omitReturnValue: false).ConfigureAwait(false))?.Object;402 public async Task<IElementHandle> LocatorWaitForAsync(string selector, LocatorWaitForOptions options = default)403 => (await _channel.WaitForSelectorAsync(404 selector: selector,405 state: options?.State,406 timeout: options?.Timeout,407 strict: true,408 omitReturnValue: true).ConfigureAwait(false))?.Object;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),432 strict: null).ConfigureAwait(false));433 public async Task<T> EvalOnSelectorAsync<T>(string selector, string expression, object arg = null, FrameEvalOnSelectorOptions options = null)434 => ScriptsHelper.ParseEvaluateResult<T>(await _channel.EvalOnSelectorAsync(435 selector: selector,436 expression,437 arg: ScriptsHelper.SerializedArgument(arg),438 strict: options?.Strict).ConfigureAwait(false));439 public async Task<JsonElement?> EvalOnSelectorAllAsync(string selector, string script, object arg = null)440 => ScriptsHelper.ParseEvaluateResult<JsonElement?>(await _channel.EvalOnSelectorAllAsync(441 selector: selector,442 script,443 arg: ScriptsHelper.SerializedArgument(arg)).ConfigureAwait(false));444 public async Task<T> EvalOnSelectorAllAsync<T>(string selector, string script, object arg = null)445 => ScriptsHelper.ParseEvaluateResult<T>(await _channel.EvalOnSelectorAllAsync(446 selector: selector,447 script,448 arg: ScriptsHelper.SerializedArgument(arg)).ConfigureAwait(false));449 public ILocator Locator(string selector, FrameLocatorOptions options = null) => new Locator(this, selector, new() { HasTextRegex = options?.HasTextRegex, HasTextString = options?.HasTextString, Has = options?.Has });450 public async Task<IElementHandle> QuerySelectorAsync(string selector, FrameQuerySelectorOptions options = null)451 => (await _channel.QuerySelectorAsync(selector, options?.Strict).ConfigureAwait(false))?.Object;452 public async Task<IResponse> GotoAsync(string url, FrameGotoOptions options = default)453 => (await _channel.GotoAsync(454 url,455 timeout: options?.Timeout,456 waitUntil: options?.WaitUntil,457 referer: options?.Referer).ConfigureAwait(false))?.Object;458 public Task<bool> IsCheckedAsync(string selector, FrameIsCheckedOptions options = default)459 => _channel.IsCheckedAsync(selector, timeout: options?.Timeout, options?.Strict);460 public Task<bool> IsDisabledAsync(string selector, FrameIsDisabledOptions options = default)461 => _channel.IsDisabledAsync(selector, timeout: options?.Timeout, options?.Strict);462 public Task<bool> IsEditableAsync(string selector, FrameIsEditableOptions options = default)463 => _channel.IsEditableAsync(selector, timeout: options?.Timeout, options?.Strict);...

Full Screen

Full Screen

Locator.cs

Source:Locator.cs Github

copy

Full Screen

...30using Microsoft.Playwright.Helpers;31using Microsoft.Playwright.Transport.Protocol;32namespace Microsoft.Playwright.Core33{34 internal class Locator : ILocator35 {36 internal readonly Frame _frame;37 internal readonly string _selector;38 private readonly LocatorLocatorOptions _options;39 public Locator(Frame parent, string selector, LocatorLocatorOptions options = null)40 {41 _frame = parent;42 _selector = selector;43 _options = options;44 if (options?.HasTextRegex != null)45 {46 _selector += $" >> :scope:text-matches({options.HasTextRegex.ToString().EscapeWithQuotes("\"")}, {options.HasTextRegex.Options.GetInlineFlags().EscapeWithQuotes("\"")})";47 }48 if (options?.HasTextString != null)49 {50 _selector += $" >> :scope:has-text({options.HasTextString.EscapeWithQuotes("\"")})";51 }52 if (options?.Has != null)53 {54 var has = (Locator)options.Has;55 if (has._frame != _frame)56 {57 throw new ArgumentException("Inner \"has\" locator must belong to the same frame.");58 }59 _selector += " >> has=" + JsonSerializer.Serialize(has._selector);60 }61 }62 public ILocator First => new Locator(_frame, $"{_selector} >> nth=0");63 public ILocator Last => new Locator(_frame, $"{_selector} >> nth=-1");64 IPage ILocator.Page => _frame.Page;65 public async Task<IReadOnlyList<string>> AllInnerTextsAsync()66 => await EvaluateAllAsync<string[]>("ee => ee.map(e => e.innerText)").ConfigureAwait(false);67 public async Task<IReadOnlyList<string>> AllTextContentsAsync()68 => await EvaluateAllAsync<string[]>("ee => ee.map(e => e.textContent || '')").ConfigureAwait(false);69 public async Task<LocatorBoundingBoxResult> BoundingBoxAsync(LocatorBoundingBoxOptions options = null)70 => await WithElementAsync(71 async (h, _) =>72 {73 var bb = await h.BoundingBoxAsync().ConfigureAwait(false);74 if (bb == null)75 {76 return null;77 }78 return new LocatorBoundingBoxResult()79 {80 Height = bb.Height,81 Width = bb.Width,82 X = bb.X,83 Y = bb.Y,84 };85 },86 options).ConfigureAwait(false);87 public Task CheckAsync(LocatorCheckOptions options = null)88 => _frame.CheckAsync(89 _selector,90 ConvertOptions<FrameCheckOptions>(options));91 public Task ClickAsync(LocatorClickOptions options = null)92 => _frame.ClickAsync(93 _selector,94 ConvertOptions<FrameClickOptions>(options));95 public Task SetCheckedAsync(bool checkedState, LocatorSetCheckedOptions options = null)96 => checkedState ?97 CheckAsync(ConvertOptions<LocatorCheckOptions>(options))98 : UncheckAsync(ConvertOptions<LocatorUncheckOptions>(options));99 public Task<int> CountAsync()100 => _frame.QueryCountAsync(_selector);101 public Task DblClickAsync(LocatorDblClickOptions options = null)102 => _frame.DblClickAsync(_selector, ConvertOptions<FrameDblClickOptions>(options));103 public Task DispatchEventAsync(string type, object eventInit = null, LocatorDispatchEventOptions options = null)104 => _frame.DispatchEventAsync(_selector, type, eventInit, ConvertOptions<FrameDispatchEventOptions>(options));105 public Task DragToAsync(ILocator target, LocatorDragToOptions options = null)106 => _frame.DragAndDropAsync(_selector, ((Locator)target)._selector, ConvertOptions<FrameDragAndDropOptions>(options));107 public async Task<IElementHandle> ElementHandleAsync(LocatorElementHandleOptions options = null)108 => await _frame.WaitForSelectorAsync(109 _selector,110 ConvertOptions<FrameWaitForSelectorOptions>(options)).ConfigureAwait(false);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)132 => _frame.InnerHTMLAsync(_selector, ConvertOptions<FrameInnerHTMLOptions>(options));133 public Task<string> InnerTextAsync(LocatorInnerTextOptions options = null)134 => _frame.InnerTextAsync(_selector, ConvertOptions<FrameInnerTextOptions>(options));135 public Task<string> InputValueAsync(LocatorInputValueOptions options = null)136 => _frame.InputValueAsync(_selector, ConvertOptions<FrameInputValueOptions>(options));137 public Task<bool> IsCheckedAsync(LocatorIsCheckedOptions options = null)138 => _frame.IsCheckedAsync(_selector, ConvertOptions<FrameIsCheckedOptions>(options));139 public Task<bool> IsDisabledAsync(LocatorIsDisabledOptions options = null)140 => _frame.IsDisabledAsync(_selector, ConvertOptions<FrameIsDisabledOptions>(options));141 public Task<bool> IsEditableAsync(LocatorIsEditableOptions options = null)142 => _frame.IsEditableAsync(_selector, ConvertOptions<FrameIsEditableOptions>(options));143 public Task<bool> IsEnabledAsync(LocatorIsEnabledOptions options = null)144 => _frame.IsEnabledAsync(_selector, ConvertOptions<FrameIsEnabledOptions>(options));145 public Task<bool> IsHiddenAsync(LocatorIsHiddenOptions options = null)146 => _frame.IsHiddenAsync(_selector, ConvertOptions<FrameIsHiddenOptions>(options));147 public Task<bool> IsVisibleAsync(LocatorIsVisibleOptions options = null)148 => _frame.IsVisibleAsync(_selector, ConvertOptions<FrameIsVisibleOptions>(options));149 public ILocator Nth(int index)150 => new Locator(_frame, $"{_selector} >> nth={index}");151 public Task PressAsync(string key, LocatorPressOptions options = null)152 => _frame.PressAsync(_selector, key, ConvertOptions<FramePressOptions>(options));153 public Task<byte[]> ScreenshotAsync(LocatorScreenshotOptions options = null)154 => WithElementAsync(async (h, o) => await h.ScreenshotAsync(ConvertOptions<ElementHandleScreenshotOptions>(o)).ConfigureAwait(false), options);155 public Task ScrollIntoViewIfNeededAsync(LocatorScrollIntoViewIfNeededOptions options = null)156 => WithElementAsync(async (h, o) => await h.ScrollIntoViewIfNeededAsync(ConvertOptions<ElementHandleScrollIntoViewIfNeededOptions>(o)).ConfigureAwait(false), options);157 public Task<IReadOnlyList<string>> SelectOptionAsync(string values, LocatorSelectOptionOptions options = null)158 => _frame.SelectOptionAsync(_selector, values, ConvertOptions<FrameSelectOptionOptions>(options));159 public Task<IReadOnlyList<string>> SelectOptionAsync(IElementHandle values, LocatorSelectOptionOptions options = null)160 => _frame.SelectOptionAsync(_selector, values, ConvertOptions<FrameSelectOptionOptions>(options));161 public Task<IReadOnlyList<string>> SelectOptionAsync(IEnumerable<string> values, LocatorSelectOptionOptions options = null)162 => _frame.SelectOptionAsync(_selector, values, ConvertOptions<FrameSelectOptionOptions>(options));163 public Task<IReadOnlyList<string>> SelectOptionAsync(SelectOptionValue values, LocatorSelectOptionOptions options = null)164 => _frame.SelectOptionAsync(_selector, values, ConvertOptions<FrameSelectOptionOptions>(options));165 public Task<IReadOnlyList<string>> SelectOptionAsync(IEnumerable<IElementHandle> values, LocatorSelectOptionOptions options = null)166 => _frame.SelectOptionAsync(_selector, values, ConvertOptions<FrameSelectOptionOptions>(options));167 public Task<IReadOnlyList<string>> SelectOptionAsync(IEnumerable<SelectOptionValue> values, LocatorSelectOptionOptions options = null)168 => _frame.SelectOptionAsync(_selector, values, ConvertOptions<FrameSelectOptionOptions>(options));169 public Task SelectTextAsync(LocatorSelectTextOptions options = null)170 => WithElementAsync((h, o) => h.SelectTextAsync(ConvertOptions<ElementHandleSelectTextOptions>(o)), options);171 public Task SetInputFilesAsync(string files, LocatorSetInputFilesOptions options = null)172 => _frame.SetInputFilesAsync(_selector, files, ConvertOptions<FrameSetInputFilesOptions>(options));173 public Task SetInputFilesAsync(IEnumerable<string> files, LocatorSetInputFilesOptions options = null)174 => _frame.SetInputFilesAsync(_selector, files, ConvertOptions<FrameSetInputFilesOptions>(options));175 public Task SetInputFilesAsync(FilePayload files, LocatorSetInputFilesOptions options = null)176 => _frame.SetInputFilesAsync(_selector, files, ConvertOptions<FrameSetInputFilesOptions>(options));177 public Task SetInputFilesAsync(IEnumerable<FilePayload> files, LocatorSetInputFilesOptions options = null)178 => _frame.SetInputFilesAsync(_selector, files, ConvertOptions<FrameSetInputFilesOptions>(options));179 public Task TapAsync(LocatorTapOptions options = null)180 => _frame.TapAsync(_selector, ConvertOptions<FrameTapOptions>(options));181 public Task<string> TextContentAsync(LocatorTextContentOptions options = null)182 => _frame.TextContentAsync(_selector, ConvertOptions<FrameTextContentOptions>(options));183 public Task TypeAsync(string text, LocatorTypeOptions options = null)184 => _frame.TypeAsync(_selector, text, ConvertOptions<FrameTypeOptions>(options));185 public Task UncheckAsync(LocatorUncheckOptions options = null)186 => _frame.UncheckAsync(_selector, ConvertOptions<FrameUncheckOptions>(options));187 ILocator ILocator.Locator(string selector, LocatorLocatorOptions options)188 => new Locator(_frame, $"{_selector} >> {selector}", options);189 public Task WaitForAsync(LocatorWaitForOptions options = null)190 => _frame.LocatorWaitForAsync(_selector, ConvertOptions<LocatorWaitForOptions>(options));191 internal Task<FrameExpectResult> ExpectAsync(string expression, FrameExpectOptions options = null)192 => _frame.ExpectAsync(193 _selector,194 expression,195 options);196 public override string ToString() => "Locator@" + _selector;197 private T ConvertOptions<T>(object source)198 where T : class, new()199 {200 T target = new();201 var targetType = target.GetType();202 if (source != null)203 {204 var sourceType = source.GetType();205 foreach (var sourceProperty in sourceType.GetProperties())206 {207 var targetProperty = targetType.GetProperty(sourceProperty.Name);208 if (targetProperty != null)209 {210 targetProperty.SetValue(target, sourceProperty.GetValue(source));211 }212 }213 }214 var strictProperty = targetType.GetProperty("Strict");215 if (strictProperty != null && strictProperty.GetValue(target) == null)216 {217 strictProperty.SetValue(target, true);218 }219 return target;220 }221 private async Task<TResult> WithElementAsync<TOptions, TResult>(Func<IElementHandle, TOptions, Task<TResult>> callback, TOptions options)222 where TOptions : class223 where TResult : class224 {225 IElementHandle handle = await ElementHandleAsync(ConvertOptions<LocatorElementHandleOptions>(options)).ConfigureAwait(false);226 try227 {228 return await callback(handle, options).ConfigureAwait(false);229 }230 finally231 {232 await handle.DisposeAsync().ConfigureAwait(false);233 }234 }235 private async Task WithElementAsync<TOptions>(Func<IElementHandle, TOptions, Task> callback, TOptions options)236 where TOptions : class237 {238 IElementHandle handle = await ElementHandleAsync(ConvertOptions<LocatorElementHandleOptions>(options)).ConfigureAwait(false);239 try240 {241 await callback(handle, options).ConfigureAwait(false);242 }243 finally244 {245 await handle.DisposeAsync().ConfigureAwait(false);246 }247 }248 public Task HighlightAsync() => _frame.HighlightAsync(_selector);249 }250}...

Full Screen

Full Screen

AssertionsBase.cs

Source:AssertionsBase.cs Github

copy

Full Screen

...31namespace Microsoft.Playwright.Core32{33 internal class AssertionsBase34 {35 public AssertionsBase(ILocator actual, bool isNot)36 {37 ActualLocator = (Locator)actual;38 IsNot = isNot;39 }40 protected bool IsNot { get; private set; }41 internal Locator ActualLocator { get; private set; }42 internal async Task ExpectImplAsync(string expression, ExpectedTextValue textValue, object expected, string message, FrameExpectOptions options)43 {44 await ExpectImplAsync(expression, new ExpectedTextValue[] { textValue }, expected, message, options).ConfigureAwait(false);45 }46 internal async Task ExpectImplAsync(string expression, ExpectedTextValue[] expectedText, object expected, string message, FrameExpectOptions options)47 {48 options = options ?? new();49 options.ExpectedText = expectedText;50 options.IsNot = IsNot;51 await ExpectImplAsync(expression, options, expected, message).ConfigureAwait(false);52 }53 internal async Task ExpectImplAsync(string expression, FrameExpectOptions expectOptions, object expected, string message)54 {55 if (expectOptions.Timeout == null)56 {57 expectOptions.Timeout = 5_000;58 }59 if (expectOptions.IsNot)60 {61 message = message.Replace("expected to", "expected not to");62 }63 var result = await ActualLocator.ExpectAsync(expression, expectOptions).ConfigureAwait(false);64 if (result.Matches == IsNot)65 {66 var actual = result.Received;67 var log = string.Join("\n", result.Log);68 if (!string.IsNullOrEmpty(log))69 {70 log = "\nCall log:\n" + log;71 }72 if (expected == null)73 {74 throw new PlaywrightException($"{message} {log}");75 }76 throw new PlaywrightException($"{message} '{FormatValue(expected)}'\nBut was: '{FormatValue(actual)}' {log}");77 }...

Full Screen

Full Screen

PlaywrightIPhoneTest.cs

Source:PlaywrightIPhoneTest.cs Github

copy

Full Screen

...21 var context = await browser.NewContextAsync(playwright.Devices["iPhone 11 Pro"]); // Complete list of devices - https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/server/deviceDescriptorsSource.json22 var page = await context.NewPageAsync();23 try {24 await page.GotoAsync("https://www.google.co.in/");25 await page.Locator("[aria-label='Search']").ClickAsync();26 await page.FillAsync("[aria-label='Search']", "BrowserStack");27 await page.Keyboard.PressAsync("Enter");28 await page.Locator("[aria-current='page']").WaitForAsync();29 var title = await page.TitleAsync();30 if (title == "BrowserStack - Google Search")31 {32 // following line of code is responsible for marking the status of the test on BrowserStack as 'passed'. You can use this code in your after hook after each test33 await MarkTestStatus("passed", "Title matched", page);34 } else {35 await MarkTestStatus("failed", "Title did not match", page);36 }37 }38 catch (Exception err) {39 await MarkTestStatus("failed", err.Message, page);40 }41 await browser.CloseAsync();42 }...

Full Screen

Full Screen

PlaywrightPixelTest.cs

Source:PlaywrightPixelTest.cs Github

copy

Full Screen

...21 var context = await browser.NewContextAsync(playwright.Devices["Pixel 5"]); // Complete list of devices - https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/server/deviceDescriptorsSource.json22 var page = await context.NewPageAsync();23 try {24 await page.GotoAsync("https://www.google.co.in/");25 await page.Locator("[aria-label='Search']").ClickAsync();26 await page.FillAsync("[aria-label='Search']", "BrowserStack");27 await page.Keyboard.PressAsync("Enter");28 await page.Locator("[aria-current='page']").WaitForAsync();29 var title = await page.TitleAsync();30 if (title == "BrowserStack - Google Search")31 {32 // following line of code is responsible for marking the status of the test on BrowserStack as 'passed'. You can use this code in your after hook after each test33 await MarkTestStatus("passed", "Title matched", page);34 } else {35 await MarkTestStatus("failed", "Title did not match", page);36 }37 }38 catch (Exception err) {39 await MarkTestStatus("failed", err.Message, page);40 }41 await browser.CloseAsync();42 }...

Full Screen

Full Screen

FrameLocator.cs

Source:FrameLocator.cs Github

copy

Full Screen

...30using System.Threading.Tasks;31using Microsoft.Playwright.Helpers;32namespace Microsoft.Playwright.Core33{34 internal class FrameLocator : IFrameLocator35 {36 private readonly Frame _frame;37 private readonly string _frameSelector;38 public FrameLocator(Frame parent, string selector)39 {40 _frame = parent;41 _frameSelector = selector;42 }43 IFrameLocator IFrameLocator.First => new FrameLocator(_frame, $"{_frameSelector} >> nth=0");44 IFrameLocator IFrameLocator.Last => new FrameLocator(_frame, $"{_frameSelector} >> nth=-1");45 IFrameLocator IFrameLocator.FrameLocator(string selector) => new FrameLocator(_frame, $"{_frameSelector} >> control=enter-frame >> {selector}");46 ILocator IFrameLocator.Locator(string selector, FrameLocatorLocatorOptions options) => new Locator(_frame, $"{_frameSelector} >> control=enter-frame >> {selector}", new() { HasTextRegex = options?.HasTextRegex, HasTextString = options?.HasTextString });47 IFrameLocator IFrameLocator.Nth(int index) => new FrameLocator(_frame, $"{_frameSelector} >> nth={index}");48 }49}...

Full Screen

Full Screen

Assertions.cs

Source:Assertions.cs Github

copy

Full Screen

2namespace Microsoft.Playwright3{4 public static class Assertions5 {6 public static ILocatorAssertions Expect(ILocator locator) => new LocatorAssertions(locator, false);7 public static IPageAssertions Expect(IPage page) => new PageAssertions(page, false);8 }9}...

Full Screen

Full Screen

Locator

Using AI Code Generation

copy

Full Screen

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 BrowserTypeLaunchOptions10 {11 });12 var page = await browser.NewPageAsync();13 await page.TypeAsync("input[name=q]", "Hello World");14 await page.ClickAsync("input[type=submit]");15 await page.WaitForSelectorAsync("text=Hello World");16 await page.ScreenshotAsync(new PageScreenshotOptions { Path = "screenshot.png" });17 }18 }19}20using Microsoft.Playwright;21using System;22using System.Threading.Tasks;23{24 {25 static async Task Main(string[] args)26 {27 using var playwright = await Playwright.CreateAsync();28 await using var browser = await playwright.Firefox.LaunchAsync(new BrowserTypeLaunchOptions29 {30 });31 var page = await browser.NewPageAsync();32 await page.TypeAsync("input[name=q]", "Hello World");33 await page.ClickAsync("input[type=submit]");34 await page.WaitForSelectorAsync("text=Hello World");35 await page.ScreenshotAsync(new PageScreenshotOptions { Path = "screenshot.png" });36 }37 }38}39using Microsoft.Playwright;40using System;41using System.Threading.Tasks;42{43 {44 static async Task Main(string[] args)45 {46 using var playwright = await Playwright.CreateAsync();47 await using var browser = await playwright.Webkit.LaunchAsync(new BrowserTypeLaunchOptions48 {49 });50 var page = await browser.NewPageAsync();51 await page.TypeAsync("input[name=q]", "Hello World");52 await page.ClickAsync("input[type=submit]");53 await page.WaitForSelectorAsync("text=Hello

Full Screen

Full Screen

Locator

Using AI Code Generation

copy

Full Screen

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 BrowserTypeLaunchOptions10 {11 });12 var page = await browser.NewPageAsync();13 await page.TypeAsync("input[name=q]", "Hello World");14 await page.ClickAsync("input[type=submit]");15 await page.WaitForSelectorAsync("text=Hello World");16 await page.ScreenshotAsync(new PageScreenshotOptions { Path = "screenshot.png" });17 }18 }19}20using Microsoft.Playwright;21using System;

Full Screen

Full Screen

Locator

Using AI Code Generation

copy

Full Screen

1using Microsoft.Playwright;2using Microsoft.Playwright.Core;3using System;4using System.Collections.Generic;5using System.Text;6{7 {8 static async System.Threading.Tasks.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 var googleSearch = page.Locator("input[title='Search']");16 await googleSearch.FillAsync("Playwright");17 await googleSearch.PressAsync("Enter");18 await page.WaitForLoadStateAsync();19 await page.ScreenshotAsync(path: "screenshot.png");20 }21 }22}23using Microsoft.Playwright;24using Microsoft.Playwright.Core;25using System;26using System.Collections.Generic;27using System.Text;28{29 {30 static async System.Threading.Tasks.Task Main(string[] args)31 {32 using var playwright = await Playwright.CreateAsync();33 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions34 {35 });36 var page = await browser.NewPageAsync();37 var googleSearch = page.Locator("input[title='Search']");38 await googleSearch.FillAsync("Playwright");39 await googleSearch.PressAsync("Enter");40 await page.WaitForLoadStateAsync();41 await page.ScreenshotAsync(path: "screenshot.png");42 }43 }44}45using Microsoft.Playwright;46using Microsoft.Playwright.Core;47using System;48using System.Collections.Generic;49using System.Text;50{51 {52 static async System.Threading.Tasks.Task Main(string[] args)53 {54 using var playwright = await Playwright.CreateAsync();55 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions56 {57using System.Threading.Tasks;58{59 {60 static async Task Main(string[] args)61 {62 using var playwright = await Playwright.CreateAsync();63 await using var browser = await playwright.Firefox.LaunchAsync(new BrowserTypeLaunchOptions64 {65 });66 var page = await browser.NewPageAsync();67 await page.TypeAsync("input[name=q]", "Hello World");68 await page.ClickAsync("input[type=submit]");69 await page.WaitForSelectorAsync("text=Hello World");70 await page.ScreenshotAsync(new PageScreenshotOptions { Path = "screenshot.png" });71 }72 }73}74using Microsoft.Playwright;75using System;76using System.Threading.Tasks;77{78 {79 static async Task Main(string[] args)80 {81 using var playwright = await Playwright.CreateAsync();82 await using var browser = await playwright.Webkit.LaunchAsync(new BrowserTypeLaunchOptions83 {84 });85 var page = await browser.NewPageAsync();86 await page.TypeAsync("input[name=q]", "Hello World");87 await page.ClickAsync("input[type=submit]");88 await page.WaitForSelectorAsync("text=Hello

Full Screen

Full Screen

Locator

Using AI Code Generation

copy

Full Screen

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 var searchInput = await page.LocatorAsync("input[name='q']");14 await searchInput.FillAsync("Playwright");15 await searchInput.PressAsync("Enter");16 await page.ScreenshotAsync(new PageScreenshotOptions17 {18 });19 }20 }21}

Full Screen

Full Screen

Locator

Using AI Code Generation

copy

Full Screen

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 var searchInput = await page.LocatorAsync("input[name='q']");14 await searchInput.FillAsync("Playwright");15 await searchInput.PressAsync("Enter");16 await page.ScreenshotAsync(new PageScreenshotOptions17 {18 });19 }20 }21}

Full Screen

Full Screen

Locator

Using AI Code Generation

copy

Full Screen

1var browser = await Playwright.CreateAsync().Chromium.LaunchAsync(new LaunchOptions { Headless = false });2var page = await browser.NewPageAsync();3await page.ClickAsync("text=Images");4var browser = await Playwright.CreateAsync().Chromium.LaunchAsync(new LaunchOptions { Headless = false });5var page = await browser.NewPageAsync();6await page.ClickAsync("text=Images");7await page.ClickAsync("css=div > a > img");8var browser = await Playwright.CreateAsync().Chromium.LaunchAsync(new LaunchOptions { Headless = false });9var page = await browser.NewPageAsync();10await page.ClickAsync("text=Images");11await page.ClickAsync("css=div > a > img");12await page.ClickAsync("css=div > a > img");13var browser = await Playwright.CreateAsync().Chromium.LaunchAsync(new LaunchOptions { Headless = false });14var page = await browser.NewPageAsync();

Full Screen

Full Screen

Locator

Using AI Code Generation

copy

Full Screen

1await page.ClickAsync("css=div > a > img");2await page.ClickAsync("css=div > a > img");3await page.ClickAsync("css=div > a > img");4using System;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 var element = await page.LocatorAsync("input[title='Search']");17 await element.TypeAsync("Hello World");18 await page.ScreenshotAsync(new PageScreenshotOptions { Path = "screenshot.png" });19 }20 }21}22using System;23using System.Threading.Tasks;24using Microsoft.Playwright;25{26 {27 static async Task Main(string[] args)28 {29 using var playwright = await Playwright.CreateAsync();30 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions31 {32 });33 var page = await browser.NewPageAsync();34 var element = await page.LocatorAsync("input[title='Search']");35 await element.TypeAsync("Hello World");36 await page.ScreenshotAsync(new PageScreenshotOptions { Path = "screenshot.png" });37 }38 }39}40using System;41using System.Threading.Tasks;42using Microsoft.Playwright;43{44 {45 static async Task Main(string[] args)46 {47 using var playwright = await Playwright.CreateAsync();48 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions49 {50 });51 var page = await browser.NewPageAsync();52 var element = await page.LocatorAsync("input[title='Search']");53 await element.TypeAsync("Hello54var browser = await Playwright.CreateAsync().Chromium.LaunchAsync(new LaunchOptions { Headless = false });55var page = await browser.NewPageAsync();56await page.ClickAsync("text=Images");57await page.ClickAsync("css=div > a > img");58await page.ClickAsync("css=div > a > img");59await page.ClickAsync("css=div > a > img");60await page.ClickAsync("css=div > a > img");

Full Screen

Full Screen

Locator

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using Microsoft.Playwright;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 BrowserTypeLaunchOptions10 {11 });12 var page = await browser.NewPageAsync();13 var element = await page.LocatorAsync("input[title='Search']");14 await element.TypeAsync("Hello World");15 await page.ScreenshotAsync(new PageScreenshotOptions { Path = "screenshot.png" });16 }17 }18}19using System;20using System.Threading.Tasks;21using Microsoft.Playwright;22{23 {24 static async Task Main(string[] args)25 {26 using var playwright = await Playwright.CreateAsync();27 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions28 {29 });30 var page = await browser.NewPageAsync();31 var element = await page.LocatorAsync("input[title='Search']");32 await element.TypeAsync("Hello World");33 await page.ScreenshotAsync(new PageScreenshotOptions { Path = "screenshot.png" });34 }35 }36}37using System;38using System.Threading.Tasks;39using Microsoft.Playwright;40{41 {42 static async Task Main(string[] args)43 {44 using var playwright = await Playwright.CreateAsync();45 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions46 {47 });48 var page = await browser.NewPageAsync();49 var element = await page.LocatorAsync("input[title='Search']");50 await element.TypeAsync("Hello

Full Screen

Full Screen

Playwright tutorial

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.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful