public virtual async Task Cocoon_Should_Honor_The_Auth_State_From_The_Legacy_App() { // Arrange using var playwright = await Playwright.CreateAsync(); await using var browser = await playwright.Firefox.LaunchAsync(BrowserTypeLaunchOptions); // Act var page = await browser.NewPageAsync(); // Login await page.GotoAsync($"{BaseUrl}/Account/Login"); await page.FillAsync("#MainContent_UserName", "admin"); await page.FillAsync("#MainContent_Password", "Pa$$word"); await page.ClickAsync("input[type='submit']"); // Find the nav bar item, can take some time as blazor has to reinit var accountLink = await page.WaitForSelectorAsync("#account-link", new PageWaitForSelectorOptions { Timeout = 3000 }); var result = await accountLink.GetAttributeAsync("title"); // Assert result.Should().Be("Manage your account"); }
public async Task AuthIsPreservedBetweenSessions() { using var playwright = await Playwright.CreateAsync(); await using var browser = await playwright.Chromium.LaunchAsync(); var context = await browser.NewContextAsync(); // Sign in and save authentication state var page = await context.NewPageAsync(); await page.GotoAsync("https://localhost:44362"); await page.ClickAsync("button:has-text(\"Sign in\")"); await context.StorageStateAsync( new BrowserContextStorageStateOptions { Path = "temp-auth-state.json" }); await context.CloseAsync(); // Open a new browser context var newContext = await browser.NewContextAsync( new BrowserNewContextOptions { StorageStatePath = "temp-auth-state.json" }); // Root page should redirect to Facilities page var newPage = await newContext.NewPageAsync(); await newPage.GotoAsync("https://localhost:44362"); newPage.Url.Should().Be("https://localhost:44362/Facilities"); }
static async Task Main() { var client = new KameleoLocalApiClient(new Uri($"http://localhost:{KameleoPort}")); client.SetRetryPolicy(null); // Search Firefox Base Profiles var baseProfiles = await client.SearchBaseProfilesAsync(deviceType : "desktop", browserProduct : "firefox"); // Create a new profile with recommended settings // for browser fingerprint protection var requestBody = BuilderForCreateProfile .ForBaseProfile(baseProfiles[0].Id) .SetRecommendedDefaults() .Build(); var profile = await client.CreateProfileAsync(requestBody); // Start the browser await client.StartProfileAsync(profile.Id); // Connect to the browser with Playwright var browserWsEndpoint = $"ws://localhost:{KameleoPort}/playwright/{profile.Id}"; var playwright = await Playwright.CreateAsync(); var browser = await playwright.Firefox.LaunchAsync(new BrowserTypeLaunchOptions { // The Playwright framework is not designed to connect to already running // browsers. To overcome this limitation, a tool bundled with Kameleo, named // pw-bridge.exe will bridge the communication gap between the running Firefox // instance and this playwright script. ExecutablePath = "<PATH_TO_KAMELEO_FOLDER>\\pw-bridge.exe", Args = new List <string> { $"-target {browserWsEndpoint}" }, }); // Kameleo will open the a new page in the default browser context. // NOTE: We DO NOT recommend using multiple browser contexts, as this might interfere // with Kameleo's browser fingerprint modification features. var page = await browser.NewPageAsync(); // Use any Playwright command to drive the browser // and enjoy full protection from bot detection products await page.GotoAsync("https://google.com"); await page.ClickAsync("div[aria-modal='true'][tabindex='0'] button + button"); await page.ClickAsync("[name=q]"); await page.Keyboard.TypeAsync("Kameleo"); await page.Keyboard.PressAsync("Enter"); // Wait for 5 seconds await page.WaitForTimeoutAsync(5000); // Stop the browser by stopping the Kameleo profile await client.StopProfileAsync(profile.Id); }
public static async Task Main() { using var playwright = await Playwright.CreateAsync(); await using var browser = await playwright.Chromium.LaunchAsync(); var page = await browser.NewPageAsync(); await page.GotoAsync("https://www.google.com/"); // Fill an input. await page.FillAsync(".gLFyf", "桂素伟"); // Navigate implicitly by clicking a link. await page.ClickAsync(".gNO89b"); // Expect a new url. Console.WriteLine(page.Url); await page.GotoAsync(page.Url); // var response = await page.GotoAsync("https://playwright.dev/dotnet"); //var body = await response.BodyAsync(); //var content = Encoding.UTF8.GetString(body); //Console.WriteLine(content); var path = $"{DateTime.Now.ToString("yyyyMMddHHmmssfff")}.png"; var imageBytes = await page.ScreenshotAsync(new PageScreenshotOptions { Path = path, FullPage = true }); File.WriteAllBytes($"{Directory.GetCurrentDirectory()}/{ path}", imageBytes); }
private static async Task ShowsCookieOnClick() { using var playwright = await Playwright.CreateAsync(); await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions { Headless = false, Channel = "msedge" }); var context = await browser.NewContextAsync(); var page = await context.NewPageAsync(); await page.GotoAsync("https://localhost:5001", new PageGotoOptions { WaitUntil = WaitUntilState.NetworkIdle }); await page.Locator("a:has-text(\"Fortune cookies\")").ClickAsync(); await page.Locator("text=Show me my cookie").ClickAsync(); var element = page.Locator("div.alert.alert-info"); Assert.NotNull(element); var text = await element.InnerTextAsync(); Assert.Contains(text, SeedData.Cookies); }
public async Task LocationSearch_WithDangerousCoordinates_ReturnsTable() { using var playwright = await Playwright.CreateAsync(); await using var browser = await playwright.Chromium.LaunchAsync(); var context = await browser.NewContextAsync(); var page = await context.NewPageAsync(); // Go to Location Search page and sign in await page.GotoAsync("https://localhost:44362/Facilities/Map"); await page.ClickAsync("button:has-text(\"Sign in\")"); (await page.TitleAsync()).Should().EndWith("Location Search"); // Fill in form await page.FillAsync("input[name=\"Spec.Latitude\"]", "33.1"); await page.FillAsync("input[name=\"Spec.Longitude\"]", "-83.5"); await page.SelectOptionAsync("select[name=\"Spec.Output\"]", new[] { "2" }); await page.ClickAsync("button:has-text(\"Search\")"); page.Url.Should().EndWith("#SearchResults"); (await page.TextContentAsync("tbody td a")).Should().Contain("FMS-183"); }
public async Task InitializeAsync() { var browserOptions = new BrowserTypeLaunchOptions { Headless = false, SlowMo = SlowMo }; // Add support to modify BaseUrl from outside. string?isGitHubActions = Environment.GetEnvironmentVariable("IsGitHubActions"); string?baseUrl = Environment.GetEnvironmentVariable("BaseUrl"); if (isGitHubActions == "true") { // Assume it's in GitHub actions and we want to run it fast. browserOptions.Headless = true; browserOptions.SlowMo = null; baseUrl ??= "https://autoscrum.jkdev.me"; } if (!string.IsNullOrWhiteSpace(baseUrl)) { BaseUrl = baseUrl; } PlaywrightInstance = await Playwright.CreateAsync(); Browser = await PlaywrightInstance.Chromium.LaunchAsync(browserOptions); BrowserContext = await Browser.NewContextAsync(); Page = await BrowserContext.NewPageAsync(); await Page.GotoAsync(BaseUrl); }
protected override async Task BeforeExecutionAsync(IExecutionContext context) { var builder = WebApplication.CreateBuilder(); builder.Logging.ClearProviders(); builder.Services .AddRazorPages() .WithRazorPagesRoot("/src/SocialCards/"); _app = builder.Build(); _app.MapRazorPages(); _app.UseStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider( Path.Combine(builder.Environment.ContentRootPath, "src/SocialCards")), RequestPath = "/static" }); await _app.StartAsync().ConfigureAwait(false); _playwright = await Playwright.CreateAsync().ConfigureAwait(false); _browser = await _playwright.Chromium.LaunchAsync().ConfigureAwait(false); _context = await _browser.NewContextAsync(new BrowserNewContextOptions { ViewportSize = new ViewportSize { Width = 1200, Height = 618 }, }).ConfigureAwait(false); }
public async Task RecorderGeneratedMSTest() { using var playwright = await Playwright.CreateAsync(); await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions { Headless = false, Channel = "msedge", }); var context = await browser.NewContextAsync(); // Open new page var page = await context.NewPageAsync(); // Go to https://playwright.dev/ await page.GotoAsync("https://playwright.dev/"); // Click text=Docs await page.ClickAsync("text=Docs"); Assert.AreEqual("https://playwright.dev/docs/intro", page.Url); // Click text=Supported languages await page.ClickAsync("text=Supported languages"); Assert.AreEqual("https://playwright.dev/docs/languages", page.Url); // Click article >> text=.NET await page.ClickAsync("article >> text=.NET"); Assert.AreEqual("https://playwright.dev/docs/languages#net", page.Url); }
static async Task Main(string[] args) { using var playwright = await Playwright.CreateAsync(); await using var browser = await playwright.Chromium.LaunchAsync(headless : true); var context = await browser.NewContextAsync(); var page = await context.NewPageAsync(); DateTime startTime; DateTime endTime; TimeSpan diffTime; string result; for (int i = 0; i < 10; i++) { startTime = DateTime.Now; await page.GoToAsync("https://www.google.com"); endTime = DateTime.Now; diffTime = endTime.Subtract(startTime); result = $"google\t\t\t\t{diffTime}\t{startTime}\t{endTime}"; Console.WriteLine(result); } }
static async Task Main(string[] args) { Console.WriteLine("Installing playwright"); await Playwright.InstallAsync(); ILoggerFactory loggerFactory = LoggerFactory.Create(builder => { builder.SetMinimumLevel(LogLevel.Debug); builder.AddDebug(); builder.AddFilter((f, _) => f == "PlaywrightSharp.Playwright"); }); using var playwright = await Playwright.CreateAsync(loggerFactory, debug : "pw:api"); await using var browser = await playwright.Chromium.LaunchAsync(new LaunchOptions { Headless = true }); var page = await browser.NewPageAsync(); Console.WriteLine("Navigating google"); await page.GoToAsync("http://www.google.com"); Console.WriteLine("Generating PDF"); await page.GetPdfAsync(Path.Combine(Directory.GetCurrentDirectory(), "google.pdf")); Console.WriteLine("Export completed"); }
public async Task BeforeLandingPageScenario(IObjectContainer container) { var playwright = await Playwright.CreateAsync(); var browser = await playwright.Chromium.LaunchAsync(); var context = await browser.NewContextAsync(new BrowserNewContextOptions { IgnoreHTTPSErrors = true }); if (_configuration.GetValue <bool>("EnableTracing")) { await context.Tracing.StartAsync(new TracingStartOptions { Screenshots = true, Snapshots = true }); } var pageObject = new LandingPageObject(context, _configuration); container.RegisterInstanceAs(playwright); container.RegisterInstanceAs(browser); container.RegisterInstanceAs(context); container.RegisterInstanceAs(pageObject); }
public async Task Test1() { Console.WriteLine("Installing playwright"); await Playwright.InstallAsync(); Console.WriteLine("Creating playwright"); var playwright = await Playwright.CreateAsync(); }
private async Task <IBrowser> GetBrowserAsync() { await Playwright.InstallAsync(); var playwright = await Playwright.CreateAsync(); return(await playwright.Chromium.LaunchAsync(headless : false)); }
public async virtual Task InitializeAsync() { _host = CreateHost(); await _host.StartAsync(); _playright = await Playwright.CreateAsync(); Browser = await _playright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions() /*Headless = false*/ }
private async Task <List <TEntity> > GetPersonsFromSearchEngineTrackAsync(string url, string query) { var entities = new List <TEntity>(); using var playwright = await Playwright.CreateAsync(); await using var browser = await playwright.Webkit.LaunchAsync(headless : false); var page = await browser.NewPageAsync(); await page.GoToAsync(url); var searchBar = "//input[@name='search']"; await page.TypeAsync(searchBar, query); await page.PressAsync(searchBar, "Enter"); await page.WaitForLoadStateAsync(LifecycleEvent.Networkidle); var pageButtons = page.QuerySelectorAsync(".gsc-cursor-page"); if (pageButtons != null) { for (int i = 2; i < 11; i++) { var dataBlocks = await page.QuerySelectorAllAsync(".gsc-webResult.gsc-result"); foreach (var block in dataBlocks) { var entity = await GetDataAsync(block); if (entity != null && !string.IsNullOrEmpty(entity.Url)) { entities.Add(entity); } } var nextButton = await page.QuerySelectorAsync($".gsc-cursor-page[aria-label='Page {i}']"); if (nextButton == null) { break; } try { await page.ClickAsync($".gsc-cursor-page[aria-label='Page {i}']"); } catch (Exception) { break; } } } return(entities); }
public async Task GetSearchPage() { string url = "https://cse.google.com/cse?cx=009462381166450434430:dqo-6rxvieq"; string query = "'developer' 'moscow' 'gmail' -intitle:'profiles' -inurl:'dir/' site:ru.linkedin.com/in/"; using var playwright = await Playwright.CreateAsync(); await using var browser = await playwright.Webkit.LaunchAsync(headless : false); var page = await browser.NewPageAsync(); await page.GoToAsync(url); // gsc-i-id1 // name var searchBar = "//input[@name='search']"; await page.TypeAsync(searchBar, query); // await page.PressAsync(searchBar, "Enter"); var buttonSearch = ".gsc-search-button.gsc-search-button-v2"; await page.ClickAsync(buttonSearch); await page.WaitForLoadStateAsync(LifecycleEvent.Networkidle); var timeout = (int)TimeSpan.FromSeconds(1).TotalMilliseconds; var pageButtons = page.QuerySelectorAsync(".gsc-cursor-page"); if (pageButtons != null) { for (int i = 2; i < 11; i++) { // Intercept network requests await page.RouteAsync("**", (route, _) => { Console.WriteLine($"step {i}"); Console.WriteLine(route.Request.Url); route.ContinueAsync(); //string newUrl = route.Request.Url.Replace("page=2", $"page={i}"); //route.ContinueAsync(url: newUrl); }); var dataBlocks = await page.QuerySelectorAllAsync(".gsc-webResult.gsc-result"); foreach (var block in dataBlocks) { await GetData(page, block); } await page.ClickAsync($".gsc-cursor-page[aria-label='Page {i}']", timeout); //await page.ClickAsync($".gsc-cursor-page[aria-label='Page 2']", timeout); } } }
public async Task FacilityWithUniqueCoordinatesCanBeAdded() { using var playwright = await Playwright.CreateAsync(); await using var browser = await playwright.Chromium.LaunchAsync(); var context = await browser.NewContextAsync(); var page = await context.NewPageAsync(); // Go to Add Facility page and sign in await page.GotoAsync("https://localhost:44362/Facilities/Add"); await page.ClickAsync("button:has-text(\"Sign in\")"); (await page.TitleAsync()).Should().EndWith("Add Facility"); // Fill in form var facilityNumber = Guid.NewGuid().ToString(); await page.ClickAsync("input[name=\"Facility.FacilityNumber\"]"); await page.FillAsync("input[name=\"Facility.FacilityNumber\"]", facilityNumber); await page.PressAsync("select[name=\"Facility.CountyId\"]", "ArrowDown"); await page.PressAsync("select[name=\"Facility.FacilityTypeId\"]", "ArrowDown"); await page.PressAsync("select[name=\"Facility.OrganizationalUnitId\"]", "ArrowDown"); await page.PressAsync("select[name=\"Facility.BudgetCodeId\"]", "ArrowDown"); await page.PressAsync("select[name=\"Facility.FacilityStatusId\"]", "ArrowDown"); await page.FillAsync("input[name=\"Facility.Name\"]", "A"); await page.FillAsync("input[name=\"Facility.Address\"]", "2"); await page.FillAsync("input[name=\"Facility.City\"]", "B"); await page.FillAsync("input[name=\"Facility.PostalCode\"]", "12345"); await page.FillAsync("input[name=\"Facility.Latitude\"]", "30"); await page.FillAsync("input[name=\"Facility.Longitude\"]", "-80"); // Submit form await page.ClickAsync("text=Create New Facility"); (await page.TitleAsync()).Should().EndWith(facilityNumber); (await page.TextContentAsync("h1")).Should().Contain(facilityNumber); // Clean up so test can be re-run await page.ClickAsync("text=Delete"); await page.ClickAsync("button:has-text(\"Delete Facility\")"); }
public async Task RequestPageWithSearch() { string url = "https://cse.google.com/cse?cx=009462381166450434430:dqo-6rxvieq"; string query = "'developer' 'moscow' 'gmail' -intitle:'profiles' -inurl:'dir/' site:ru.linkedin.com/in/"; using var playwright = await Playwright.CreateAsync(); await using var browser = await playwright.Webkit.LaunchAsync(headless : false); var page = await browser.NewPageAsync(); await page.GoToAsync(url); // gsc-i-id1 // name var searchBar = "//input[@name='search']"; await page.TypeAsync(searchBar, query); // await page.PressAsync(searchBar, "Enter"); var buttonSearch = ".gsc-search-button.gsc-search-button-v2"; var responseTcs = new TaskCompletionSource <IResponse>(); page.Response += (sender, e) => { responseTcs.TrySetResult(e.Response); }; await page.ClickAsync(buttonSearch); var response = await responseTcs.Task; var json = await response.GetTextAsync(); //page.Response += Page_Response; //await page.ClickAsync(buttonSearch); //page.Response -= Page_Response; // var timeout = (int)TimeSpan.FromSeconds(1).TotalMilliseconds; // var requestTask = page.WaitForRequestAsync(requestUrl, timeout); // var responseTask = page.WaitForResponseAsync(requestUrl, timeout); //// await page.GoToAsync("https://github.com/microsoft/playwright-sharp"); // await Task.WhenAll(requestTask, responseTask); //using(HttpClient client = new HttpClient()) //{ // var response = await client.GetAsync(requestUrl); // if (response.IsSuccessStatusCode) // await response.Content.ReadAsStringAsync(); //} await page.WaitForLoadStateAsync(LifecycleEvent.Networkidle); }
public WebDriverFixture() { playwright = Playwright.CreateAsync().Result; var options = new BrowserTypeLaunchOptions() { Headless = Headless, }; browser = playwright.Chromium.LaunchAsync(options); }
public async Task WithPageAsync( Func <IPage, Task> action, string browserType = "chromium", [CallerMemberName] string?testName = null) { using var playwright = await Playwright.CreateAsync(); await using var browser = await CreateBrowserAsync(playwright, browserType); var options = CreateContextOptions(); await using var context = await browser.NewContextAsync(options); if (IsRunningInGitHubActions) { await context.Tracing.StartAsync(new() { Screenshots = true, Snapshots = true, Sources = true, Title = testName, }); } var page = await context.NewPageAsync(); page.Console += (_, e) => OutputHelper.WriteLine(e.Text); page.PageError += (_, e) => OutputHelper.WriteLine(e); try { await action(page); } catch (Exception) { if (IsRunningInGitHubActions) { string traceName = GenerateFileName(testName !, browserType, ".zip"); string path = Path.Combine("traces", traceName); await context.Tracing.StopAsync(new() { Path = path }); OutputHelper.WriteLine($"Trace saved to {path}."); } await TryCaptureScreenshotAsync(page, testName !, browserType); throw; } finally { await TryCaptureVideoAsync(page, testName !, browserType); } }
public async Task NavigateToPage() { using var pw = await Playwright.CreateAsync(); await using var browser = await pw.Chromium.LaunchAsync(headless : false); var page = await browser.NewPageAsync(); await page.GoToAsync("http://the-internet.herokuapp.com/"); Assert.True(await page.IsVisibleAsync("css=h1[class='heading']")); }
public async Task GetScreenShot() { using var playwright = await Playwright.CreateAsync(); await using var browser = await playwright.Chromium.LaunchAsync(); var page = await browser.NewPageAsync(); await page.GoToAsync("http://www.google.com"); await page.ScreenshotAsync(path : "screen.jpg"); }
public static async Task Main() { using var playwright = await Playwright.CreateAsync(); await using var browser = await playwright.Chromium.LaunchAsync(); var page = await browser.NewPageAsync(); await page.GotoAsync("https://github.com/microsoft/playwright"); await page.PdfAsync(new PagePdfOptions { Path = "page.pdf" }); }
public static async Task Main(string[] args) { using var playwright = await Playwright.CreateAsync(); await using var browser = await playwright.Firefox.LaunchAsync(headless : false); var page = await browser.NewPageAsync(); await page.GoToAsync("https://www.bing.com"); await page.ScreenshotAsync(path : "GoBind.png"); }
private async Task <Result <ScrapeResult> > ScrapeManganelo(string url, string mediaName) { try { using var playwright = await Playwright.CreateAsync(); await using var browser = await playwright.Chromium.LaunchAsync(new LaunchOptions { Headless = true }); var page = await browser.NewPageAsync(); await page.GoToAsync(url); var container = await page.WaitForSelectorAsync("div.panel-story-chapter-list", WaitForState.Visible); var chapters = await container.QuerySelectorAsync("ul.row-content-chapter"); var newestChapter = await chapters.QuerySelectorAsync("li.a-h"); var newestLink = await newestChapter.QuerySelectorAsync("a"); var chapterUrl = await newestLink.GetAttributeAsync("href"); var regexResult = Regex.Match(chapterUrl, @"chapter_(\d{1,4})\.*(\d{0,4})"); var releaseNumberString = regexResult.Groups[1].Value; var subReleaseNumberString = regexResult.Groups[2].Value; if (!int.TryParse(releaseNumberString, out var releaseNumber)) { _logger.LogError("Releasenumber could not be extracted from link {chapterUrl} for media {mediaName}", chapterUrl, mediaName); return(Result.Failure <ScrapeResult>($"Releasenumber could not be extracted from link {chapterUrl} for media {mediaName}")); } var subReleaseNumber = 0; if (!string.IsNullOrEmpty(subReleaseNumberString)) { if (!int.TryParse(subReleaseNumberString, out subReleaseNumber)) { return(Result.Failure <ScrapeResult>($"SubReleaseNumber could not be extracted from link {chapterUrl} for media {mediaName}")); } } return(Result.Success(new ScrapeResult { MediaName = mediaName, ReleaseNumber = releaseNumber, SubReleaseNumber = subReleaseNumber, Url = chapterUrl })); } catch (Exception e) { _logger.LogError("Something went wrong while scraping for media {media}. {exceptionMessage}", mediaName, e.Message); return(Result.Failure <ScrapeResult>($"Scraping for media {mediaName} failed due to {e.Message}")); } }
public async Task Test1() { await Playwright.InstallAsync(); using var playwright = await Playwright.CreateAsync(); await using var browser = await playwright.Chromium.LaunchAsync(headless : false); var page = await browser.NewPageAsync(); await page.GoToAsync("http://www.google.com"); }
public Tests(ITestOutputHelper outputHelper) { outputHelper.WriteLine("Setting up browser drivers. This might take awhile"); Playwright.InstallAsync().GetAwaiter().GetResult(); Environment.SetEnvironmentVariable("PWDEBUG", "1"); Environment.SetEnvironmentVariable("DEBUG", "pw:api"); playwright = Playwright.CreateAsync().GetAwaiter().GetResult(); outputHelper.WriteLine("Finished setting up browser drivers"); this.outputHelper = outputHelper; }
public async Task TestInit() { using var playwright = await Playwright.CreateAsync(); await using var browser = await playwright.Chromium.LaunchAsync(true); var page = await browser.NewPageAsync(); await page.GoToAsync("https://autenti.com"); await page.ScreenshotAsync(path : "screenshot.png"); }
public static async Task Main() { using var playwright = await Playwright.CreateAsync(); await using var browser = await playwright.Chromium.LaunchAsync(); var page = await browser.NewPageAsync(); page.Request += (_, request) => Console.WriteLine(">> " + request.Method + " " + request.Url); page.Response += (_, response) => Console.WriteLine("<<" + response.Status + " " + response.Url); await page.GotoAsync("https://example.com"); }