Best Playwright-dotnet code snippet using Microsoft.Playwright.Core.Locator
Frame.cs
Source:Frame.cs
...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);...
Locator.cs
Source:Locator.cs
...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}...
AssertionsBase.cs
Source:AssertionsBase.cs
...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 }...
PageAssertions.cs
Source:PageAssertions.cs
...29{30 internal class PageAssertions : AssertionsBase, IPageAssertions31 {32 private readonly Page _page;33 public PageAssertions(IPage page, bool isNot) : base(PassThroughNonNull(page).Locator(":root"), isNot)34 {35 _page = (Page)page;36 }37 public IPageAssertions Not => new PageAssertions(_page, !IsNot);38 private static T PassThroughNonNull<T>(T value)39 {40 if (value == null)41 {42 throw new ArgumentNullException(nameof(value));43 }44 return value;45 }46 public Task ToHaveTitleAsync(string titleOrRegExp, PageAssertionsToHaveTitleOptions options = null) =>47 ExpectImplAsync("to.have.title", new ExpectedTextValue() { String = titleOrRegExp, NormalizeWhiteSpace = true }, titleOrRegExp, "Page title expected to be", ConvertToFrameExpectOptions(options));...
PlaywrightIPhoneTest.cs
Source:PlaywrightIPhoneTest.cs
...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 }...
PlaywrightPixelTest.cs
Source:PlaywrightPixelTest.cs
...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 }...
FrameLocator.cs
Source:FrameLocator.cs
...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}...
Assertions.cs
Source:Assertions.cs
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}...
Locator
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 var playwright = await Playwright.CreateAsync();9 var browser = await playwright.Chromium.LaunchAsync();10 var page = await browser.NewPageAsync();11 await page.ScreenshotAsync("google.png");12 await browser.CloseAsync();13 }14 }15}
Locator
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 await using var playwright = await Playwright.CreateAsync();9 await using var browser = await playwright.Chromium.LaunchAsync();10 var page = await browser.NewPageAsync();11 var locator = page.Locator("input[name=q]");12 await locator.TypeAsync("Hello World");13 await locator.PressAsync("Enter");14 }15 }16}17using Microsoft.Playwright;18using System;19using System.Threading.Tasks;20{21 {22 static async Task Main(string[] args)23 {24 await using var playwright = await Playwright.CreateAsync();25 await using var browser = await playwright.Chromium.LaunchAsync();26 var page = await browser.NewPageAsync();27 var locator = page.Locator("input[name=q]");28 await locator.TypeAsync("Hello World");29 await locator.PressAsync("Enter");30 }31 }32}33using Microsoft.Playwright.NUnit;34using NUnit.Framework;35using System.Threading.Tasks;36{37 {38 public async Task LocatorTest()39 {40 await using var playwright = await Playwright.CreateAsync();41 await using var browser = await playwright.Chromium.LaunchAsync();42 var page = await browser.NewPageAsync();43 var locator = page.Locator("input[name=q]");44 await locator.TypeAsync("Hello World");45 await locator.PressAsync("Enter");46 }47 }48}49using Microsoft.Playwright.Xunit;50using System.Threading.Tasks;51using Xunit;52using Xunit.Abstractions;53{
Locator
Using AI Code Generation
1using Microsoft.Playwright.Core;2using System;3using System.Threading.Tasks;4{5 {6 static async Task Main()7 {8 var playwright = await Playwright.CreateAsync();9 var browser = await playwright.Chromium.LaunchAsync();10 var page = await browser.NewPageAsync();11 await page.ClickAsync("text=Google apps");12 await page.ClickAsync("text=YouTube");13 var locator = new Locator(page, "text=YouTube");14 var element = await locator.GetElementAsync();15 var text = await element.TextContentAsync();16 Console.WriteLine(text);17 await browser.CloseAsync();18 }19 }20}21using Microsoft.Playwright;22using System;23using System.Threading.Tasks;24{25 {26 static async Task Main()27 {28 var playwright = await Playwright.CreateAsync();29 var browser = await playwright.Chromium.LaunchAsync();30 var page = await browser.NewPageAsync();31 await page.ClickAsync("text=Google apps");32 await page.ClickAsync("text=YouTube");33 var locator = new Locator(page, "text=YouTube");34 var element = await locator.GetElementAsync();35 var text = await element.TextContentAsync();36 Console.WriteLine(text);37 await browser.CloseAsync();38 }39 }40}41using Microsoft.Playwright;42using System;43using System.Threading.Tasks;44{45 {46 static async Task Main()47 {48 var playwright = await Playwright.CreateAsync();49 var browser = await playwright.Chromium.LaunchAsync();50 var page = await browser.NewPageAsync();51 await page.ClickAsync("text=Google apps");52 await page.ClickAsync("text=YouTube");53 var locator = new Locator(page, "text=YouTube");54 var element = await locator.GetElementAsync();55 var text = await element.TextContentAsync();56 Console.WriteLine(text);57 await browser.CloseAsync();58 }59 }60}
Locator
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 await Playwright.InstallAsync();10 var playwright = await Playwright.CreateAsync();11 await using var browser = await playwright.Chromium.LaunchAsync();12 var page = await browser.NewPageAsync();13 var locator = page.Locator("input[name=q]");14 await locator.FillAsync("Playwright");15 await page.Keyboard.PressAsync("Enter");
Locator
Using AI Code Generation
1using Microsoft.Playwright.Core;2using PlaywrightSharp;3using System;4using System.Threading.Tasks;5{6 {7 static async Task Main(string[] args)8 {9 var browserPath = Locator.FindExecutable();10 using var playwright = await Playwright.CreateAsync();11 var browser = await playwright.Chromium.LaunchAsync(new LaunchOptions12 {13 });14 var page = await browser.NewPageAsync();15 var title = page.Title;16 Console.WriteLine(title);17 await browser.CloseAsync();18 }19 }20}
Locator
Using AI Code Generation
1{2 public Locator(IElementHandle elementHandle)3 {4 this.elementHandle = elementHandle;5 }6 public IElementHandle elementHandle;7 public Locator ElementHandle { get; set; }8 public Locator ElementHandle2 { get; set; }9}10{11 public Locator(IElementHandle elementHandle)12 {13 this.elementHandle = elementHandle;14 }15 public IElementHandle elementHandle;16 public Locator ElementHandle { get; set; }17 public Locator ElementHandle2 { get; set; }18}19{20 public Locator(IElementHandle elementHandle)21 {22 this.elementHandle = elementHandle;23 }24 public IElementHandle elementHandle;25 public Locator ElementHandle { get; set; }26 public Locator ElementHandle2 { get; set; }27}28{29 public Locator(IElementHandle elementHandle)30 {31 this.elementHandle = elementHandle;32 }33 public IElementHandle elementHandle;34 public Locator ElementHandle { get; set; }35 public Locator ElementHandle2 { get; set; }36}37{38 public Locator(IElementHandle elementHandle)39 {40 this.elementHandle = elementHandle;41 }42 public IElementHandle elementHandle;43 public Locator ElementHandle { get; set; }44 public Locator ElementHandle2 { get; set; }45}46{47 public Locator(IElementHandle elementHandle)48 {49 this.elementHandle = elementHandle;50 }51 public IElementHandle elementHandle;52 public Locator ElementHandle { get; set; }53 public Locator ElementHandle2 { get; set; }54}55{56 public Locator(IElementHandle elementHandle)57 {58 this.elementHandle = elementHandle;59 }60 public IElementHandle elementHandle;
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!!