Best Playwright-dotnet code snippet using Microsoft.Playwright.Core.Frame.QuerySelectorAsync
Page.cs
Source:Page.cs
...366 public Task<T> EvalOnSelectorAsync<T>(string selector, string expression, object arg = null, PageEvalOnSelectorOptions options = null)367 => MainFrame.EvalOnSelectorAsync<T>(selector, expression, arg, new() { Strict = options?.Strict });368 public ILocator Locator(string selector, PageLocatorOptions options = default)369 => MainFrame.Locator(selector, new() { HasTextString = options?.HasTextString, HasTextRegex = options?.HasTextRegex, Has = options?.Has });370 public Task<IElementHandle> QuerySelectorAsync(string selector, PageQuerySelectorOptions options = null)371 => MainFrame.QuerySelectorAsync(selector, new() { Strict = options?.Strict });372 public Task<T> EvalOnSelectorAsync<T>(string selector, string expression, object arg) => MainFrame.EvalOnSelectorAsync<T>(selector, expression, arg);373 public Task<JsonElement?> EvalOnSelectorAllAsync(string selector, string expression, object arg) => MainFrame.EvalOnSelectorAllAsync(selector, expression, arg);374 public Task<T> EvalOnSelectorAllAsync<T>(string selector, string expression, object arg) => MainFrame.EvalOnSelectorAllAsync<T>(selector, expression, arg);375 public Task FillAsync(string selector, string value, PageFillOptions options = default)376 => MainFrame.FillAsync(selector, value, new() { NoWaitAfter = options?.NoWaitAfter, Timeout = options?.Timeout, Force = options?.Force, Strict = options?.Strict });377 public Task SetInputFilesAsync(string selector, string files, PageSetInputFilesOptions options = default)378 => MainFrame.SetInputFilesAsync(selector, files, Map(options));379 public Task SetInputFilesAsync(string selector, IEnumerable<string> files, PageSetInputFilesOptions options = default)380 => MainFrame.SetInputFilesAsync(selector, files, Map(options));381 public Task SetInputFilesAsync(string selector, FilePayload files, PageSetInputFilesOptions options = default)382 => MainFrame.SetInputFilesAsync(selector, files, Map(options));383 public Task SetInputFilesAsync(string selector, IEnumerable<FilePayload> files, PageSetInputFilesOptions options = default)384 => MainFrame.SetInputFilesAsync(selector, files, Map(options));385 public Task TypeAsync(string selector, string text, PageTypeOptions options = default)386 => MainFrame.TypeAsync(selector, text, new()387 {388 Delay = options?.Delay,389 NoWaitAfter = options?.NoWaitAfter,390 Timeout = options?.Timeout,391 Strict = options?.Strict,392 });393 public Task FocusAsync(string selector, PageFocusOptions options = default)394 => MainFrame.FocusAsync(selector, new()395 {396 Timeout = options?.Timeout,397 Strict = options?.Strict,398 });399 public Task HoverAsync(string selector, PageHoverOptions options = default)400 => MainFrame.HoverAsync(401 selector,402 new()403 {404 Position = options?.Position,405 Modifiers = options?.Modifiers,406 Force = options?.Force,407 Timeout = options?.Timeout,408 Trial = options?.Trial,409 Strict = options?.Strict,410 });411 public Task PressAsync(string selector, string key, PagePressOptions options = default)412 => MainFrame.PressAsync(selector, key, new()413 {414 Delay = options?.Delay,415 NoWaitAfter = options?.NoWaitAfter,416 Timeout = options?.Timeout,417 Strict = options?.Strict,418 });419 public Task<IReadOnlyList<string>> SelectOptionAsync(string selector, string values, PageSelectOptionOptions options = default)420 => SelectOptionAsync(selector, new[] { values }, options);421 public Task<IReadOnlyList<string>> SelectOptionAsync(string selector, IEnumerable<string> values, PageSelectOptionOptions options = default)422 => SelectOptionAsync(selector, values.Select(x => new SelectOptionValue() { Value = x }), options);423 public Task<IReadOnlyList<string>> SelectOptionAsync(string selector, IElementHandle values, PageSelectOptionOptions options = default)424 => SelectOptionAsync(selector, new[] { values }, options);425 public Task<IReadOnlyList<string>> SelectOptionAsync(string selector, IEnumerable<IElementHandle> values, PageSelectOptionOptions options = default)426 => MainFrame.SelectOptionAsync(selector, values, new()427 {428 NoWaitAfter = options?.NoWaitAfter,429 Timeout = options?.Timeout,430 Force = options?.Force,431 Strict = options?.Strict,432 });433 public Task<IReadOnlyList<string>> SelectOptionAsync(string selector, SelectOptionValue values, PageSelectOptionOptions options = default)434 => SelectOptionAsync(selector, new[] { values }, options);435 public Task<IReadOnlyList<string>> SelectOptionAsync(string selector, IEnumerable<SelectOptionValue> values, PageSelectOptionOptions options = default)436 => MainFrame.SelectOptionAsync(selector, values, new()437 {438 NoWaitAfter = options?.NoWaitAfter,439 Timeout = options?.Timeout,440 Force = options?.Force,441 Strict = options?.Strict,442 });443 public Task WaitForTimeoutAsync(float timeout) => MainFrame.WaitForTimeoutAsync(timeout);444 public Task<IElementHandle> WaitForSelectorAsync(string selector, PageWaitForSelectorOptions options = default)445 => MainFrame.WaitForSelectorAsync(selector, new()446 {447 State = options?.State,448 Timeout = options?.Timeout,449 Strict = options?.Strict,450 });451 public Task<JsonElement?> EvaluateAsync(string expression, object arg) => MainFrame.EvaluateAsync(expression, arg);452 public async Task<byte[]> ScreenshotAsync(PageScreenshotOptions options = default)453 {454 options ??= new PageScreenshotOptions();455 if (options.Type == null && !string.IsNullOrEmpty(options.Path))456 {457 options.Type = ElementHandle.DetermineScreenshotType(options.Path);458 }459 byte[] result = await _channel.ScreenshotAsync(460 path: options.Path,461 fullPage: options.FullPage,462 clip: options.Clip,463 omitBackground: options.OmitBackground,464 type: options.Type,465 quality: options.Quality,466 mask: options.Mask,467 animations: options.Animations,468 caret: options.Caret,469 scale: options.Scale,470 timeout: options.Timeout).ConfigureAwait(false);471 if (!string.IsNullOrEmpty(options.Path))472 {473 Directory.CreateDirectory(new FileInfo(options.Path).Directory.FullName);474 File.WriteAllBytes(options.Path, result);475 }476 return result;477 }478 public Task SetContentAsync(string html, PageSetContentOptions options = default)479 => MainFrame.SetContentAsync(html, new() { WaitUntil = options?.WaitUntil, Timeout = options?.Timeout });480 public Task<string> ContentAsync() => MainFrame.ContentAsync();481 public Task SetExtraHTTPHeadersAsync(IEnumerable<KeyValuePair<string, string>> headers)482 => _channel.SetExtraHTTPHeadersAsync(headers);483 public Task<IElementHandle> QuerySelectorAsync(string selector) => MainFrame.QuerySelectorAsync(selector);484 public Task<IReadOnlyList<IElementHandle>> QuerySelectorAllAsync(string selector)485 => MainFrame.QuerySelectorAllAsync(selector);486 public Task<IJSHandle> EvaluateHandleAsync(string expression, object arg) => MainFrame.EvaluateHandleAsync(expression, arg);487 public Task<IElementHandle> AddScriptTagAsync(PageAddScriptTagOptions options = default)488 => MainFrame.AddScriptTagAsync(new()489 {490 Url = options?.Url,491 Path = options?.Path,492 Content = options?.Content,493 Type = options?.Type,494 });495 public Task<IElementHandle> AddStyleTagAsync(PageAddStyleTagOptions options = default)496 => MainFrame.AddStyleTagAsync(new()497 {...
Frame.cs
Source:Frame.cs
...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);464 public Task<bool> IsEnabledAsync(string selector, FrameIsEnabledOptions options = default)465 => _channel.IsEnabledAsync(selector, timeout: options?.Timeout, options?.Strict);...
FrameChannel.cs
Source:FrameChannel.cs
...57 serverParams?.ToObject<FrameChannelLoadStateEventArgs>(Connection.DefaultJsonSerializerOptions));58 break;59 }60 }61 internal Task<ElementHandleChannel> QuerySelectorAsync(string selector, bool? strict)62 {63 var args = new Dictionary<string, object>64 {65 ["selector"] = selector,66 ["strict"] = strict,67 };68 return Connection.SendMessageToServerAsync<ElementHandleChannel>(Guid, "querySelector", args);69 }70 internal Task<ResponseChannel> GotoAsync(string url, float? timeout, WaitUntilState? waitUntil, string referer)71 {72 var args = new Dictionary<string, object>73 {74 ["url"] = url,75 ["timeout"] = timeout,76 ["waitUntil"] = waitUntil,77 ["referer"] = referer,78 };79 return Connection.SendMessageToServerAsync<ResponseChannel>(Guid, "goto", args);80 }81 internal Task<JSHandleChannel> EvaluateExpressionHandleAsync(82 string script,83 object arg)84 {85 return Connection.SendMessageToServerAsync<JSHandleChannel>(86 Guid,87 "evaluateExpressionHandle",88 new Dictionary<string, object>89 {90 ["expression"] = script,91 ["arg"] = arg,92 });93 }94 internal Task<JSHandleChannel> WaitForFunctionAsync(95 string expression,96 object arg,97 float? timeout,98 float? polling)99 {100 var args = new Dictionary<string, object>101 {102 ["expression"] = expression,103 ["arg"] = arg,104 ["timeout"] = timeout,105 ["pollingInterval"] = polling,106 };107 return Connection.SendMessageToServerAsync<JSHandleChannel>(108 Guid,109 "waitForFunction",110 args);111 }112 internal Task<JsonElement?> EvaluateExpressionAsync(113 string script,114 object arg)115 {116 return Connection.SendMessageToServerAsync<JsonElement?>(117 Guid,118 "evaluateExpression",119 new Dictionary<string, object>120 {121 ["expression"] = script,122 ["arg"] = arg,123 });124 }125 internal Task<JsonElement?> EvalOnSelectorAsync(string selector, string script, object arg, bool? strict)126 => Connection.SendMessageToServerAsync<JsonElement?>(127 Guid,128 "evalOnSelector",129 new Dictionary<string, object>130 {131 ["selector"] = selector,132 ["expression"] = script,133 ["arg"] = arg,134 ["strict"] = strict,135 });136 internal Task<JsonElement?> EvalOnSelectorAllAsync(string selector, string script, object arg)137 => Connection.SendMessageToServerAsync<JsonElement?>(138 Guid,139 "evalOnSelectorAll",140 new Dictionary<string, object>141 {142 ["selector"] = selector,143 ["expression"] = script,144 ["arg"] = arg,145 });146 internal Task<ElementHandleChannel> FrameElementAsync() => Connection.SendMessageToServerAsync<ElementHandleChannel>(Guid, "frameElement", null);147 internal async Task<string> TitleAsync()148 => (await Connection.SendMessageToServerAsync(Guid, "title", null).ConfigureAwait(false))?.GetProperty("value").ToString();149 internal Task<ElementHandleChannel> WaitForSelectorAsync(string selector, WaitForSelectorState? state, float? timeout, bool? strict, bool? omitReturnValue)150 {151 var args = new Dictionary<string, object>152 {153 ["selector"] = selector,154 ["timeout"] = timeout,155 ["state"] = state,156 ["strict"] = strict,157 ["omitReturnValue"] = omitReturnValue,158 };159 return Connection.SendMessageToServerAsync<ElementHandleChannel>(160 Guid,161 "waitForSelector",162 args);163 }164 internal Task WaitForTimeoutAsync(float timeout)165 {166 var args = new Dictionary<string, object>167 {168 ["timeout"] = timeout,169 };170 return Connection.SendMessageToServerAsync<ElementHandleChannel>(171 Guid,172 "waitForTimeout",173 args);174 }175 internal Task<ElementHandleChannel> AddScriptTagAsync(string url, string path, string content, string type)176 {177 var args = new Dictionary<string, object>178 {179 ["url"] = url,180 ["path"] = path,181 ["content"] = content,182 ["type"] = type,183 };184 return Connection.SendMessageToServerAsync<ElementHandleChannel>(Guid, "addScriptTag", args);185 }186 internal Task<ElementHandleChannel> AddStyleTagAsync(string url, string path, string content)187 {188 var args = new Dictionary<string, object>189 {190 ["url"] = url,191 ["path"] = path,192 ["content"] = content,193 };194 return Connection.SendMessageToServerAsync<ElementHandleChannel>(Guid, "addStyleTag", args);195 }196 internal Task<ResponseChannel> WaitForNavigationAsync(LoadState? waitUntil, string url, float? timeout)197 {198 var param = new Dictionary<string, object>199 {200 ["timeout"] = timeout,201 ["url"] = url,202 ["waitUntil"] = waitUntil,203 };204 return Connection.SendMessageToServerAsync<ResponseChannel>(Guid, "waitForNavigation", param);205 }206 internal Task WaitForLoadStateAsync(LoadState? state, float? timeout)207 {208 var param = new Dictionary<string, object>209 {210 ["timeout"] = timeout,211 ["state"] = state,212 };213 return Connection.SendMessageToServerAsync(214 Guid,215 "waitForLoadState",216 param);217 }218 internal async Task<int> QueryCountAsync(string selector)219 {220 var args = new Dictionary<string, object>221 {222 ["selector"] = selector,223 };224 var result = await Connection.SendMessageToServerAsync(Guid, "queryCount", args).ConfigureAwait(false);225 return result.Value.GetProperty("value").GetInt32();226 }227 internal Task SetContentAsync(string html, float? timeout, WaitUntilState? waitUntil)228 {229 var args = new Dictionary<string, object>230 {231 ["html"] = html,232 ["waitUntil"] = waitUntil,233 ["timeout"] = timeout,234 };235 return Connection.SendMessageToServerAsync(Guid, "setContent", args);236 }237 internal Task ClickAsync(238 string selector,239 float? delay,240 MouseButton? button,241 int? clickCount,242 IEnumerable<KeyboardModifier> modifiers,243 Position position,244 float? timeout,245 bool? force,246 bool? noWaitAfter,247 bool? trial,248 bool? strict)249 {250 var args = new Dictionary<string, object>251 {252 ["selector"] = selector,253 ["button"] = button,254 ["force"] = force,255 ["delay"] = delay,256 ["clickCount"] = clickCount,257 ["modifiers"] = modifiers?.Select(m => m.ToValueString()),258 ["position"] = position,259 ["noWaitAfter"] = noWaitAfter,260 ["trial"] = trial,261 ["timeout"] = timeout,262 ["strict"] = strict,263 };264 return Connection.SendMessageToServerAsync<ElementHandleChannel>(Guid, "click", args);265 }266 internal Task DblClickAsync(267 string selector,268 float? delay,269 MouseButton? button,270 Position position,271 IEnumerable<KeyboardModifier> modifiers,272 float? timeout,273 bool? force,274 bool? noWaitAfter,275 bool? trial,276 bool? strict)277 {278 var args = new Dictionary<string, object>279 {280 ["selector"] = selector,281 ["button"] = button,282 ["delay"] = delay,283 ["force"] = force,284 ["modifiers"] = modifiers?.Select(m => m.ToValueString()),285 ["position"] = position,286 ["trial"] = trial,287 ["timeout"] = timeout,288 ["noWaitAfter"] = noWaitAfter,289 ["strict"] = strict,290 };291 return Connection.SendMessageToServerAsync<ElementHandleChannel>(Guid, "dblclick", args);292 }293 internal Task<ElementHandleChannel> QuerySelectorAsync(string selector)294 => Connection.SendMessageToServerAsync<ElementHandleChannel>(295 Guid,296 "querySelector",297 new Dictionary<string, object>298 {299 ["selector"] = selector,300 });301 internal Task<ChannelBase[]> QuerySelectorAllAsync(string selector)302 => Connection.SendMessageToServerAsync<ChannelBase[]>(303 Guid,304 "querySelectorAll",305 new Dictionary<string, object>306 {307 ["selector"] = selector,...
PlaygroundTests.cs
Source:PlaygroundTests.cs
...280 using var playwright = await Playwright.CreateAsync();281 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions { Headless = true });282 var page = await browser.NewPageAsync();283 await page.GotoAsync("https://play.tailwindcss.com/");284 var iframe = await page.QuerySelectorAsync("iframe");285 var expected = await (await iframe!.ContentFrameAsync())!.ContentAsync();286 var diffs = DiffBuilder287 .Compare(expected)288 .WithTest(actual)289 .Build()290 .ToList();291 diffs.Should().BeEmpty();292 }293 [Test]294 public async Task statiq_web_examples()295 {296 // https://github.com/statiqdev/Statiq.Web297 // cd /examples/Statiq.Web.Examples298 // dotnet run -- preview...
ProcessService.cs
Source:ProcessService.cs
...79 var page = await browser.NewPageAsync();80 81 await page.GotoAsync(searchUrl);82 // get result count for validation83 IElementHandle resultEls = await page.QuerySelectorAsync(".search-form__count");84 int resultsCount = 0;85 int pages = resultEls != null86 ? int.TryParse(ResultCountRegex.Match(await resultEls.InnerTextAsync()).Groups["ResultCount"].Value, out resultsCount)87 ? (int)Math.Ceiling((decimal)resultsCount / 10)88 : 189 : 1;90 var results = new Results {Expected = resultsCount};91 92 _logger?.LogInformation("Expecting {ResultsCount} results", resultsCount);93 // iterate pages of adverts94 for (var i = 1; i <= pages; i++)95 {96 _logger?.LogInformation("Processing page {Page}", i);97 98 // if this isn't the first page then append the page number and navigate99 if (i > 1)100 {101 var navPage = searchUrl.SetQueryParam("page", i);102 103 results.Pages.Add(navPage);104 105 await page.GotoAsync(navPage);106 }107 else108 results.Pages.Add(searchUrl);109 // get adverts on page110 var ads = await page.QuerySelectorAllAsync("article.product-card[data-standout-type=''] > a");111 112 // iterate all adverts113 foreach (var ad in ads)114 {115 // build a car object116 var car = new Car(await ad.GetAttributeAsync("href"));117 118 _logger?.LogInformation("Processing ad {Url}", car.Url);119 120 // open the advert in a new browser page121 IPage adPage = await browser.NewPageAsync();122 await adPage.GotoAsync(car.Url.AsFullUrl(_searchSettings.Domain));123 124 // wait 1 second to try and improve image quality of snapshot125 Thread.Sleep(1000);126 127 // snapshot entire ad128 var adSelector = ":is(main > div > div:nth-child(2), main > article > div:nth-child(2), main > div > div)";129 130 if (await ElementExists(adSelector, adPage, "ad image", false))131 {132 IElementHandle image = await adPage.QuerySelectorAsync(adSelector);133 134 if (image == null)135 _logger?.LogError("Failed to retrieve ad image after successfully finding the ad image element");136 else137 {138 var imageDir = Path.Combine(searchDirectory, "images");139 car.AdImage = $"{car.Id}_ad.png";140 var fullSizePath = Path.Combine(imageDir, $"{car.Id}_ad_full.png");141 142 await image.ScreenshotAsync(new ElementHandleScreenshotOptions { Path = fullSizePath });143 await using var input = File.OpenRead(fullSizePath);144 using var img = await Image.LoadAsync(input);145 img.Mutate(r => r.Resize(new ResizeOptions146 {147 Size = new Size(img.Width, img.Width),148 Mode = ResizeMode.Crop,149 Position = AnchorPositionMode.Top150 }));151 152 await img.SaveAsync(Path.Combine(imageDir, car.AdImage));153 }154 }155 #region attempts to get more granular data, not required when snapshotting entire ad156 // snapshot image157 // var imgSelector = ":is(.gallery__container, section[data-gui='gallery-section'])";158 //159 // if (await ElementExists(imgSelector, adPage, "image", false))160 // {161 // IElementHandle image = await page.QuerySelectorAsync(imgSelector);162 // 163 // if (image == null)164 // _logger.LogError("Failed to retrieve image after successfully finding the image element");165 // else166 // {167 // car.Image = $"{car.Id}.png";168 // 169 // await image.ScreenshotAsync(new ElementHandleScreenshotOptions { Path = Path.Combine(_imageDir, car.Image) });170 // }171 // }172 // get price173 // var priceSelector = "text=/£\\d{2},\\d{3}/i";174 //175 // if (await ElementExists(priceSelector, adPage, "price", false))176 // {177 // IElementHandle price = await adPage.QuerySelectorAsync(priceSelector);178 // 179 // if (price == null)180 // _logger.LogError("Failed to retrieve price after successfully finding the price element");181 // else182 // car.Price = PriceRegex.Match(await price.InnerHTMLAsync()).Groups["Price"].Value;183 // }184 // get mileage185 // var mileageSelector = "text=/\\d+,\\d+ miles/i";186 //187 // if (await ElementExists(mileageSelector, adPage, "mileage", false))188 // {189 // IElementHandle mileage = await adPage.QuerySelectorAsync(mileageSelector);190 // 191 // if (mileage == null)192 // _logger.LogError("Failed to retrieve mileage after successfully finding the mileage element");193 // else194 // car.Mileage = await mileage.InnerTextAsync();195 // }196 #endregion197 bool locationLinkFound = false;198 // try to find a location link199 try200 {201 var locBtnSelector = ":is(button[data-gui-test='dealerLocationLink'], button.seller-location__toggle)";202 if (!await ElementExists(locBtnSelector, adPage, "location"))203 {204 results.Cars.Add(car);205 206 continue;207 }208 await adPage.ClickAsync(locBtnSelector);209 210 var mapFrameSelector = "iframe[src^='https://www.google.com/maps/embed']";211 if (!await ElementExists(mapFrameSelector, adPage, "map frame", false))212 {213 results.Cars.Add(car);214 215 continue;216 }217 218 Thread.Sleep(500);219 220 var mapFrameQuery = await adPage.QuerySelectorAsync(mapFrameSelector);221 if (mapFrameQuery == null)222 {223 _logger?.LogError("Failed to find the map iframe after successfully finding the map frame element");224 225 results.Cars.Add(car);226 await adPage.CloseAsync();227 continue;228 }229 230 var mapFrame = await mapFrameQuery.ContentFrameAsync();231 if (mapFrame == null)232 {233 _logger?.LogError("Failed to select the map iframe element after successfully finding the map iframe element");234 235 results.Cars.Add(car);236 await adPage.CloseAsync();237 continue;238 }239 240 var coordsSelector = "div.place-name";241 if (await ElementExists(coordsSelector, mapFrame, "coordinates"))242 {243 IElementHandle coords = await mapFrame.QuerySelectorAsync(coordsSelector);244 245 if (coords == null)246 _logger?.LogError("Failed to retrieve coordinates after successfully finding the coordinates element");247 else248 car.Coords = await coords.InnerTextAsync();249 }250 251 var addressSelector = "div.address";252 if (await ElementExists(coordsSelector, mapFrame, "address"))253 {254 IElementHandle address = await mapFrame.QuerySelectorAsync(addressSelector);255 if (address == null)256 _logger?.LogError("Failed to retrieve address after successfully finding the address element");257 else258 car.Location = await address.InnerTextAsync();259 }260 locationLinkFound = true;261 }262 catch (Exception e)263 {264 _logger?.LogWarning(e, "Failed to find a location link for advert");265 locationLinkFound = false;266 }267 // todo - if a location link wasn't found, ust the approximate location from the summary screen268 if (!locationLinkFound)...
ElementHandleChannel.cs
Source:ElementHandleChannel.cs
...62 Guid,63 "waitForSelector",64 args);65 }66 internal Task<ElementHandleChannel> QuerySelectorAsync(string selector)67 => Connection.SendMessageToServerAsync<ElementHandleChannel>(68 Guid,69 "querySelector",70 new Dictionary<string, object>71 {72 ["selector"] = selector,73 });74 internal Task WaitForElementStateAsync(ElementState state, float? timeout)75 {76 var args = new Dictionary<string, object>77 {78 ["state"] = state,79 ["timeout"] = timeout,80 };...
ElementHandle.cs
Source:ElementHandle.cs
...148 {149 var converted = SetInputFilesHelpers.ConvertInputFiles(files);150 await _channel.SetInputFilesAsync(converted.Files, options?.NoWaitAfter, options?.Timeout).ConfigureAwait(false);151 }152 public async Task<IElementHandle> QuerySelectorAsync(string selector)153 => (await _channel.QuerySelectorAsync(selector).ConfigureAwait(false))?.Object;154 public async Task<IReadOnlyList<IElementHandle>> QuerySelectorAllAsync(string selector)155 => (await _channel.QuerySelectorAllAsync(selector).ConfigureAwait(false)).Select(e => ((ElementHandleChannel)e).Object).ToList().AsReadOnly();156 public async Task<JsonElement?> EvalOnSelectorAsync(string selector, string expression, object arg = null)157 => ScriptsHelper.ParseEvaluateResult<JsonElement?>(await _channel.EvalOnSelectorAsync(158 selector: selector,159 script: expression,160 arg: ScriptsHelper.SerializedArgument(arg)).ConfigureAwait(false));161 public async Task<T> EvalOnSelectorAsync<T>(string selector, string expression, object arg = null)162 => ScriptsHelper.ParseEvaluateResult<T>(await _channel.EvalOnSelectorAsync(163 selector: selector,164 script: expression,165 arg: ScriptsHelper.SerializedArgument(arg)).ConfigureAwait(false));166 public async Task<T> EvalOnSelectorAllAsync<T>(string selector, string expression, object arg = null)167 => ScriptsHelper.ParseEvaluateResult<T>(await _channel.EvalOnSelectorAllAsync(...
QuerySelectorAsync
Using AI Code Generation
1using Microsoft.Playwright;2using System.Threading.Tasks;3{4 static async Task Main(string[] args)5 {6 using var playwright = await Playwright.CreateAsync();7 await using var browser = await playwright.Chromium.LaunchAsync();8 var page = await browser.NewPageAsync();9 await page.QuerySelectorAsync("input");10 }11}12using Microsoft.Playwright;13using System.Threading.Tasks;14{15 static async Task Main(string[] args)16 {17 using var playwright = await Playwright.CreateAsync();18 await using var browser = await playwright.Chromium.LaunchAsync();19 var page = await browser.NewPageAsync();20 await page.QuerySelectorAllAsync("input");21 }22}23using Microsoft.Playwright;24using System.Threading.Tasks;25{26 static async Task Main(string[] args)27 {28 using var playwright = await Playwright.CreateAsync();29 await using var browser = await playwright.Chromium.LaunchAsync();30 var page = await browser.NewPageAsync();31 await page.WaitForSelectorAsync("input");32 }33}34using Microsoft.Playwright;35using System.Threading.Tasks;36{37 static async Task Main(string[] args)38 {39 using var playwright = await Playwright.CreateAsync();40 await using var browser = await playwright.Chromium.LaunchAsync();41 var page = await browser.NewPageAsync();42 await page.WaitForTimeoutAsync(1000);43 }44}45using Microsoft.Playwright;46using System.Threading.Tasks;47{48 static async Task Main(string[] args)49 {50 using var playwright = await Playwright.CreateAsync();51 await using var browser = await playwright.Chromium.LaunchAsync();52 var page = await browser.NewPageAsync();
QuerySelectorAsync
Using AI Code Generation
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()10 {11 });12 var page = await browser.NewPageAsync();13 var element = await page.QuerySelectorAsync("input[name='search']");14 await element.TypeAsync("Playwright");15 await element.PressAsync("Enter");16 await page.ScreenshotAsync("screenshot.png");17 }18 }19}20using System;21using System.Threading.Tasks;22using Microsoft.Playwright;23{24 {25 static async Task Main(string[] args)26 {27 using var playwright = await Playwright.CreateAsync();28 await using var browser = await playwright.Chromium.LaunchAsync(new()29 {30 });31 var page = await browser.NewPageAsync();32 var elements = await page.QuerySelectorAllAsync("a");33 Console.WriteLine(elements.Count);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()46 {47 });48 var page = await browser.NewPageAsync();49 var element = await page.QuerySelectorAsync("input[name='search']");50 await element.TypeAsync("Playwright");51 await element.PressAsync("Enter");52 await page.ScreenshotAsync("screenshot.png");53 }54 }55}
QuerySelectorAsync
Using AI Code Generation
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 context = await browser.NewContextAsync();13 var page = await context.NewPageAsync();14 var element = await page.QuerySelectorAsync("input[name='q']");15 await element.TypeAsync("Hello World");16 await page.PressAsync("input[name='q']", "Enter");17 Console.WriteLine("Press any key to close the browser");18 Console.ReadKey();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 context = await browser.NewContextAsync();34 var page = await context.NewPageAsync();35 var element = await page.QuerySelectorAsync("input[name='q']");36 await element.TypeAsync("Hello World");37 await page.PressAsync("input[name='q']", "Enter");38 Console.WriteLine("Press any key to close the browser");39 Console.ReadKey();40 }41 }42}
QuerySelectorAsync
Using AI Code Generation
1var playwright = await Playwright.CreateAsync();2var browser = await playwright.Chromium.LaunchAsync();3var context = await browser.NewContextAsync();4var page = await context.NewPageAsync();5await page.QuerySelectorAsync("input[name=q]");6await page.FillAsync("input[name=q]", "Playwright");7await page.Keyboard.PressAsync("Enter");8await page.WaitForNavigationAsync();9Console.WriteLine(page.Url);10await page.ScreenshotAsync("screenshot.png");11await browser.CloseAsync();12var playwright = await Playwright.CreateAsync();13var browser = await playwright.Chromium.LaunchAsync();14var context = await browser.NewContextAsync();15var page = await context.NewPageAsync();16await page.QuerySelectorAsync("input[name=q]");17await page.FillAsync("input[name=q]", "Playwright");18await page.Keyboard.PressAsync("Enter");19await page.WaitForNavigationAsync();20Console.WriteLine(page.Url);21await page.ScreenshotAsync("screenshot.png");22await browser.CloseAsync();23var playwright = await Playwright.CreateAsync();24var browser = await playwright.Chromium.LaunchAsync();25var context = await browser.NewContextAsync();26var page = await context.NewPageAsync();27await page.QuerySelectorAsync("input[name=q]");28await page.FillAsync("input[name=q]", "Playwright");29await page.Keyboard.PressAsync("Enter");30await page.WaitForNavigationAsync();31Console.WriteLine(page.Url);32await page.ScreenshotAsync("screenshot.png");33await browser.CloseAsync();34var playwright = await Playwright.CreateAsync();35var browser = await playwright.Chromium.LaunchAsync();36var context = await browser.NewContextAsync();37var page = await context.NewPageAsync();38await page.QuerySelectorAsync("input[name=q]");39await page.FillAsync("input[name=q]", "Playwright");40await page.Keyboard.PressAsync("Enter");41await page.WaitForNavigationAsync();42Console.WriteLine(page.Url);43await page.ScreenshotAsync("screenshot
QuerySelectorAsync
Using AI Code Generation
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 LaunchOptions { Headless = false });10 var page = await browser.NewPageAsync();11 await page.ClickAsync("text=Sign in");12 var element = await page.QuerySelectorAsync("input[type='email']");13 await element.TypeAsync("testuser");14 Console.WriteLine("Hello World!");15 }16 }17}18using System;19using System.Threading.Tasks;20using Microsoft.Playwright;21{22 {23 static async Task Main(string[] args)24 {25 using var playwright = await Playwright.CreateAsync();26 await using var browser = await playwright.Chromium.LaunchAsync(new LaunchOptions { Headless = false });27 var page = await browser.NewPageAsync();28 await page.ClickAsync("text=Sign in");29 var elements = await page.QuerySelectorAllAsync("input[type='email']");30 foreach (var element in elements)31 {32 await element.TypeAsync("testuser");33 }34 Console.WriteLine("Hello World!");35 }36 }37}38using System;39using System.Threading.Tasks;40using Microsoft.Playwright;41{42 {43 static async Task Main(string[] args)44 {45 using var playwright = await Playwright.CreateAsync();46 await using var browser = await playwright.Chromium.LaunchAsync(new LaunchOptions { Headless = false });47 var page = await browser.NewPageAsync();48 await page.ClickAsync("text=Sign in");49 var element = await page.QuerySelectorAsync("input[type='email']");50 await element.TypeAsync("testuser");51 var element2 = await element.QuerySelectorAsync("input[type='password']");52 await element2.TypeAsync("testpassword");
QuerySelectorAsync
Using AI Code Generation
1var playwright = await Playwright.CreateAsync();2var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions3{4});5var context = await browser.NewContextAsync();6var page = await context.NewPageAsync();7var search = await page.QuerySelectorAsync("input[name='q']");8await search.TypeAsync("Hello World");9await page.ScreenshotAsync("example.png");10await browser.CloseAsync();11var playwright = await Playwright.CreateAsync();12var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions13{14});15var context = await browser.NewContextAsync();16var page = await context.NewPageAsync();17var search = await page.QuerySelectorAsync("input[name='q']");18await search.TypeAsync("Hello World");19await page.ScreenshotAsync("example.png");20await browser.CloseAsync();21var playwright = await Playwright.CreateAsync();22var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions23{24});25var context = await browser.NewContextAsync();26var page = await context.NewPageAsync();27var search = await page.QuerySelectorAsync("input[name='q']");28await search.TypeAsync("Hello World");29await page.ScreenshotAsync("example.png");30await browser.CloseAsync();31var playwright = await Playwright.CreateAsync();32var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions33{34});35var context = await browser.NewContextAsync();36var page = await context.NewPageAsync();37var search = await page.QuerySelectorAsync("input[name='q']");38await search.TypeAsync("Hello World");39await page.ScreenshotAsync("example.png");40await browser.CloseAsync();41var playwright = await Playwright.CreateAsync();
QuerySelectorAsync
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using Microsoft.Playwright;4using Microsoft.Playwright.Core;5{6 {7 static async Task Main(string[] args)8 {9 await using var playwright = await Playwright.CreateAsync();10 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions11 {12 });13 var page = await browser.NewPageAsync();14 var element = await page.QuerySelectorAsync("input[name=q]");15 await element.TypeAsync("Hello, World!");16 await element.PressAsync("Enter");17 await page.ScreenshotAsync("google.png");18 }19 }20}21using System;22using System.Threading.Tasks;23using Microsoft.Playwright;24using Microsoft.Playwright.Core;25{26 {27 static async Task Main(string[] args)28 {29 await 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 elements = await page.QuerySelectorAllAsync("input[name=q]");35 await elements[0].TypeAsync("Hello, World!");36 await elements[0].PressAsync("Enter");37 await page.ScreenshotAsync("google.png");38 }39 }40}41using System;42using System.Threading.Tasks;43using Microsoft.Playwright;44using Microsoft.Playwright.Core;45{46 {47 static async Task Main(string[] args)48 {49 await using var playwright = await Playwright.CreateAsync();50 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions51 {52 });53 var page = await browser.NewPageAsync();54 var element = await page.QuerySelectorAsync("input[name=q]");55 await element.TypeAsync("Hello, World!");56 await element.PressAsync("Enter");
QuerySelectorAsync
Using AI Code Generation
1using Microsoft.Playwright.Core;2using System;3using System.Threading.Tasks;4{5 {6 static async Task Main(string[] args)7 {8 using var playwright = await Playwright.CreateAsync();9 await using var browser = await playwright.Chromium.LaunchAsync();10 var page = await browser.NewPageAsync();11 var searchBox = await page.QuerySelectorAsync("input[name=q]");12 await searchBox.TypeAsync("playwright");13 await searchBox.PressAsync("Enter");14 await page.WaitForNavigationAsync();15 await page.ScreenshotAsync("screenshot.png");16 }17 }18}19using Microsoft.Playwright.Core;20using System;21using System.Threading.Tasks;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();28 var page = await browser.NewPageAsync();29 var searchBox = await page.QuerySelectorAsync("input[name=q]");30 await searchBox.TypeAsync("playwright");31 await searchBox.PressAsync("Enter");32 await page.WaitForNavigationAsync();33 var result = await page.QuerySelectorAllAsync("h3");34 foreach (var item in result)35 {36 Console.WriteLine(await item.TextContentAsync());37 }38 }39 }40}41using Microsoft.Playwright.Core;42using System;43using System.Threading.Tasks;44{45 {46 static async Task Main(string[] args)47 {48 using var playwright = await Playwright.CreateAsync();49 await using var browser = await playwright.Chromium.LaunchAsync();
QuerySelectorAsync
Using AI Code Generation
1using Microsoft.Playwright;2using System;3using System.Threading.Tasks;4{5 {6 static async Task Main(string[] args)7 {8 Console.WriteLine("Hello World!");9 using var playwright = await Playwright.CreateAsync();10 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions11 {12 });13 var page = await browser.NewPageAsync();14 var element = await page.QuerySelectorAsync("input");15 await element.TypeAsync("Hello World");16 await page.PressAsync("input", "Enter");17 await page.ScreenshotAsync(new PageScreenshotOptions18 {19 });20 Console.WriteLine("Done");21 Console.ReadLine();22 }23 }24}
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!