How to use LocatorLocatorOptions class of Microsoft.Playwright package

Best Playwright-dotnet code snippet using Microsoft.Playwright.LocatorLocatorOptions

ILocator.cs

Source:ILocator.cs Github

copy

Full Screen

...428        /// A selector to use when resolving DOM element. See <a href="https://playwright.dev/dotnet/docs/selectors">working429        /// with selectors</a> for more details.430        /// </param>431        /// <param name="options">Call options</param>432        ILocator Locator(string selector, LocatorLocatorOptions? options = default);433        /// <summary>434        /// <para>435        /// Returns locator to the n-th matching element. It's zero based, <c>nth(0)</c> selects436        /// the first element.437        /// </para>438        /// </summary>439        /// <param name="index">440        /// </param>441        ILocator Nth(int index);442        /// <summary><para>A page this locator belongs to.</para></summary>443        IPage Page { get; }444        /// <summary>445        /// <para>Focuses the element, and then uses <see cref="IKeyboard.DownAsync"/> and <see cref="IKeyboard.UpAsync"/>.</para>446        /// <para>...

Full Screen

Full Screen

Locator.cs

Source:Locator.cs Github

copy

Full Screen

...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();...

Full Screen

Full Screen

PlaywrightSyncElement.cs

Source:PlaywrightSyncElement.cs Github

copy

Full Screen

...31        /// </summary>32        /// <param name="parent">The parent playwright element</param>33        /// <param name="selector">Sub element selector</param>34        /// <param name="options">Advanced locator options</param>35        public PlaywrightSyncElement(PlaywrightSyncElement parent, string selector, LocatorLocatorOptions? options = null)36        {37            this.ParentLocator = parent.ElementLocator();38            this.Selector = selector;39            this.LocatorOptions = options;40        }41        /// <summary>42        /// Initializes a new instance of the <see cref="PlaywrightSyncElement" /> class43        /// </summary>44        /// <param name="frame">The assoicated playwright frame locator</param>45        /// <param name="selector">Element selector</param>46        public PlaywrightSyncElement(IFrameLocator frame, string selector)47        {48            this.ParentFrameLocator = frame;49            this.Selector = selector;50        }51        /// <summary>52        /// Initializes a new instance of the <see cref="PlaywrightSyncElement" /> class53        /// </summary>54        /// <param name="testObject">The assoicated playwright test object</param>55        /// <param name="selector">Element selector</param>56        /// <param name="options">Advanced locator options</param>57        public PlaywrightSyncElement(IPlaywrightTestObject testObject, string selector, PageLocatorOptions? options = null) : this(testObject.PageDriver.AsyncPage, selector, options)58        {59        }60        /// <summary>61        /// Initializes a new instance of the <see cref="PlaywrightSyncElement" /> class62        /// </summary>63        /// <param name="driver">The assoicated playwright page driver</param>64        /// <param name="selector">Element selector</param>65        /// <param name="options">Advanced locator options</param>66        public PlaywrightSyncElement(PageDriver driver, string selector, PageLocatorOptions? options = null) : this(driver.AsyncPage, selector, options)67        {68        }69        /// <summary>70        /// Gets the parent async page71        /// </summary>72        public IPage? ParentPage { get; private set; }73        /// <summary>74        /// Gets the parent locator75        /// </summary>76        public ILocator? ParentLocator { get; private set; }77        /// <summary>78        /// Gets the parent frame locator79        /// </summary>80        public IFrameLocator? ParentFrameLocator { get; private set; }81        /// <summary>82        /// Gets the page locator options83        /// </summary>84        public PageLocatorOptions? PageOptions { get; private set; }85        /// <summary>86        /// Gets the page locator options87        /// </summary>88        public LocatorLocatorOptions? LocatorOptions { get; private set; }89        /// <summary>90        /// Gets the selector string91        /// </summary>92        public string Selector { get; private set; }93        /// <summary>94        /// ILocator for this element95        /// </summary>96        /// <returns></returns>97        public ILocator ElementLocator()98        {99            if (this.ParentPage != null)100            {101                return this.ParentPage.Locator(Selector, PageOptions);102            }...

Full Screen

Full Screen

LocatorLocatorOptions.cs

Source:LocatorLocatorOptions.cs Github

copy

Full Screen

...35using System.Threading.Tasks;36#nullable enable37namespace Microsoft.Playwright38{39    public class LocatorLocatorOptions40    {41        public LocatorLocatorOptions() { }42        public LocatorLocatorOptions(LocatorLocatorOptions clone)43        {44            if (clone == null)45            {46                return;47            }48            Has = clone.Has;49            HasTextString = clone.HasTextString;50            HasTextRegex = clone.HasTextRegex;51        }52        /// <summary>53        /// <para>54        /// Matches elements containing an element that matches an inner locator. Inner locator55        /// is queried against the outer one. For example, <c>article</c> that has <c>text=Playwright</c>56        /// matches <c>&lt;article&gt;&lt;div&gt;Playwright&lt;/div&gt;&lt;/article&gt;</c>....

Full Screen

Full Screen

LocatorLocatorOptions

Using AI Code Generation

copy

Full Screen

1using Microsoft.Playwright;2using Microsoft.Playwright.Core;3using Microsoft.Playwright.Helpers;4using Microsoft.Playwright.Transport;5using Microsoft.Playwright.Transport.Channels;6using Microsoft.Playwright.Transport.Protocol;7using System;8using System.Collections.Generic;9using System.Linq;10using System.Text;11using System.Threading;12using System.Threading.Tasks;13{14    {15        static async Task Main(string[] args)16        {17            var playwright = await Playwright.CreateAsync();18            var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions { Headless = false });19            var page = await browser.NewPageAsync();20            await page.TypeAsync("input[name='q']", "Playwright");21            await page.ClickAsync("input[value='Google Search']");22            {23                {24                }25            };26            var locator = await page.LocatorAsync(locatorOptions);27            await locator.ClickAsync();28            await page.ScreenshotAsync("result.png");29            await browser.CloseAsync();30        }31    }32}

Full Screen

Full Screen

LocatorLocatorOptions

Using AI Code Generation

copy

Full Screen

1using Microsoft.Playwright;2using System;3using System.Threading.Tasks;4{5    {6        static async Task Main(string[] args)7        {8            Console.WriteLine("Hello World!");9            using var playwright = await Playwright.CreateAsync();10            var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions11            {12                Args = new string[] { "--start-maximized" }13            });14            var context = await browser.NewContextAsync();15            var page = await context.NewPageAsync();16            await page.TypeAsync("input[name=q]", "Playwright");17            await page.PressAsync("input[name=q]", "Enter");18            await page.ScreenshotAsync(new PageScreenshotOptions { Path = "screenshot.png" });19            await browser.CloseAsync();20        }21    }22}23using Microsoft.Playwright;24using System;25using System.Threading.Tasks;26{27    {28        static async Task Main(string[] args)29        {30            Console.WriteLine("Hello World!");31            using var playwright = await Playwright.CreateAsync();32            var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions33            {34                Args = new string[] { "--start-maximized" }35            });36            var context = await browser.NewContextAsync();37            var page = await context.NewPageAsync();38            await page.TypeAsync("input[name=q]", "Playwright");39            await page.PressAsync("input[name=q]", "Enter");40            await page.ScreenshotAsync(new PageScreenshotOptions { Path = "screenshot.png" });41            await browser.CloseAsync();42        }43    }44}45using Microsoft.Playwright;46using System;47using System.Threading.Tasks;48{49    {50        static async Task Main(string[] args)51        {52            Console.WriteLine("Hello World!");53            using var playwright = await Playwright.CreateAsync();54            var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions

Full Screen

Full Screen

LocatorLocatorOptions

Using AI Code Generation

copy

Full Screen

1using Microsoft.Playwright;2using Microsoft.Playwright.NUnit;3using NUnit.Framework;4{5    {6        private IPage _page;7        public async Task SetUp()8        {9            var playwright = await Playwright.CreateAsync();10            var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions11            {12            });13            _page = await browser.NewPageAsync();14        }15        public async Task LocatorLocatorOptionsTest()16        {17            await _page.WaitForLoadStateAsync(LoadState.DOMContentLoaded);18            var locator = _page.Locator("input", new LocatorLocatorOptions19            {20            });21            Assert.NotNull(locator);22        }23        public async Task TearDown()24        {25            await _page.CloseAsync();26        }27    }28}29using Microsoft.Playwright;30using Microsoft.Playwright.NUnit;31using NUnit.Framework;32{33    {34        private IPage _page;35        public async Task SetUp()36        {37            var playwright = await Playwright.CreateAsync();38            var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions39            {40            });41            _page = await browser.NewPageAsync();42        }43        public async Task LocatorLocatorOptionsTest()44        {45            await _page.WaitForLoadStateAsync(LoadState.DOMContentLoaded);46            var locator = _page.Locator("input", new LocatorLocatorOptions47            {48                Text = new Regex("Google Search")49            });50            Assert.NotNull(locator);51        }52        public async Task TearDown()53        {54            await _page.CloseAsync();55        }56    }57}58using Microsoft.Playwright;59using Microsoft.Playwright.NUnit;60using NUnit.Framework;

Full Screen

Full Screen

Playwright tutorial

LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.

Chapters:

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

Run Playwright-dotnet automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used methods in LocatorLocatorOptions

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful