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

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

Run Playwright-dotnet automation tests on LambdaTest cloud grid

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

FrameLocator.cs

Source: FrameLocator.cs Github

copy
1/*
2 * MIT License
3 *
4 * Copyright (c) 2020 Darío Kondratiuk
5 * Copyright (c) 2020 Meir Blachman
6 * Modifications copyright (c) Microsoft Corporation.
7 *
8 * Permission is hereby granted, free of charge, to any person obtaining a copy
9 * of this software and associated documentation files (the "Software"), to deal
10 * in the Software without restriction, including without limitation the rights
11 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12 * copies of the Software, and to permit persons to whom the Software is
13 * furnished to do so, subject to the following conditions:
14 *
15 * The above copyright notice and this permission notice shall be included in all
16 * copies or substantial portions of the Software.
17 *
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24 * SOFTWARE.
25 */
26using System;
27using System.Collections.Generic;
28using System.Linq;
29using System.Text.Json;
30using System.Threading.Tasks;
31using Microsoft.Playwright.Helpers;
32
33namespace Microsoft.Playwright.Core
34{
35    internal class FrameLocator : IFrameLocator
36    {
37        private readonly Frame _frame;
38        private readonly string _frameSelector;
39
40        public FrameLocator(Frame parent, string selector)
41        {
42            _frame = parent;
43            _frameSelector = selector;
44        }
45
46        IFrameLocator IFrameLocator.First => new FrameLocator(_frame, $"{_frameSelector} >> nth=0");
47
48        IFrameLocator IFrameLocator.Last => new FrameLocator(_frame, $"{_frameSelector} >> nth=-1");
49
50        IFrameLocator IFrameLocator.FrameLocator(string selector) => new FrameLocator(_frame, $"{_frameSelector} >> control=enter-frame >> {selector}");
51
52        ILocator IFrameLocator.Locator(string selector, FrameLocatorLocatorOptions options) => new Locator(_frame, $"{_frameSelector} >> control=enter-frame >> {selector}", new() { HasTextRegex = options?.HasTextRegex, HasTextString = options?.HasTextString });
53
54        IFrameLocator IFrameLocator.Nth(int index) => new FrameLocator(_frame, $"{_frameSelector} >> nth={index}");
55    }
56}
57
Full Screen

Locator.cs

Source: Locator.cs Github

copy
1/*
2 * MIT License
3 *
4 * Copyright (c) 2020 Darío Kondratiuk
5 * Copyright (c) 2020 Meir Blachman
6 * Modifications copyright (c) Microsoft Corporation.
7 *
8 * Permission is hereby granted, free of charge, to any person obtaining a copy
9 * of this software and associated documentation files (the "Software"), to deal
10 * in the Software without restriction, including without limitation the rights
11 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12 * copies of the Software, and to permit persons to whom the Software is
13 * furnished to do so, subject to the following conditions:
14 *
15 * The above copyright notice and this permission notice shall be included in all
16 * copies or substantial portions of the Software.
17 *
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24 * SOFTWARE.
25 */
26using System;
27using System.Collections.Generic;
28using System.Text.Json;
29using System.Threading.Tasks;
30using Microsoft.Playwright.Helpers;
31using Microsoft.Playwright.Transport.Protocol;
32
33namespace Microsoft.Playwright.Core
34{
35    internal class Locator : ILocator
36    {
37        internal readonly Frame _frame;
38        internal readonly string _selector;
39
40        private readonly LocatorLocatorOptions _options;
41
42        public Locator(Frame parent, string selector, LocatorLocatorOptions options = null)
43        {
44            _frame = parent;
45            _selector = selector;
46            _options = options;
47
48            if (options?.HasTextRegex != null)
49            {
50                _selector += $" >> :scope:text-matches({options.HasTextRegex.ToString().EscapeWithQuotes("\"")}, {options.HasTextRegex.Options.GetInlineFlags().EscapeWithQuotes("\"")})";
51            }
52            if (options?.HasTextString != null)
53            {
54                _selector += $" >> :scope:has-text({options.HasTextString.EscapeWithQuotes("\"")})";
55            }
56
57            if (options?.Has != null)
58            {
59                var has = (Locator)options.Has;
60                if (has._frame != _frame)
61                {
62                    throw new ArgumentException("Inner \"has\" locator must belong to the same frame.");
63                }
64                _selector += " >> has=" + JsonSerializer.Serialize(has._selector);
65            }
66        }
67
68        public ILocator First => new Locator(_frame, $"{_selector} >> nth=0");
69
70        public ILocator Last => new Locator(_frame, $"{_selector} >> nth=-1");
71
72        IPage ILocator.Page => _frame.Page;
73
74        public async Task<IReadOnlyList<string>> AllInnerTextsAsync()
75            => await EvaluateAllAsync<string[]>("ee => ee.map(e => e.innerText)").ConfigureAwait(false);
76
77        public async Task<IReadOnlyList<string>> AllTextContentsAsync()
78            => await EvaluateAllAsync<string[]>("ee => ee.map(e => e.textContent || '')").ConfigureAwait(false);
79
80        public async Task<LocatorBoundingBoxResult> BoundingBoxAsync(LocatorBoundingBoxOptions options = null)
81            => await WithElementAsync(
82                async (h, _) =>
83                {
84                    var bb = await h.BoundingBoxAsync().ConfigureAwait(false);
85                    if (bb == null)
86                    {
87                        return null;
88                    }
89
90                    return new LocatorBoundingBoxResult()
91                    {
92                        Height = bb.Height,
93                        Width = bb.Width,
94                        X = bb.X,
95                        Y = bb.Y,
96                    };
97                },
98                options).ConfigureAwait(false);
99
100        public Task CheckAsync(LocatorCheckOptions options = null)
101            => _frame.CheckAsync(
102                _selector,
103                ConvertOptions<FrameCheckOptions>(options));
104
105        public Task ClickAsync(LocatorClickOptions options = null)
106            => _frame.ClickAsync(
107                _selector,
108                ConvertOptions<FrameClickOptions>(options));
109
110        public Task SetCheckedAsync(bool checkedState, LocatorSetCheckedOptions options = null)
111            => checkedState ?
112                CheckAsync(ConvertOptions<LocatorCheckOptions>(options))
113                : UncheckAsync(ConvertOptions<LocatorUncheckOptions>(options));
114
115        public Task<int> CountAsync()
116            => _frame.QueryCountAsync(_selector);
117
118        public Task DblClickAsync(LocatorDblClickOptions options = null)
119            => _frame.DblClickAsync(_selector, ConvertOptions<FrameDblClickOptions>(options));
120
121        public Task DispatchEventAsync(string type, object eventInit = null, LocatorDispatchEventOptions options = null)
122            => _frame.DispatchEventAsync(_selector, type, eventInit, ConvertOptions<FrameDispatchEventOptions>(options));
123
124        public Task DragToAsync(ILocator target, LocatorDragToOptions options = null)
125            => _frame.DragAndDropAsync(_selector, ((Locator)target)._selector, ConvertOptions<FrameDragAndDropOptions>(options));
126
127        public async Task<IElementHandle> ElementHandleAsync(LocatorElementHandleOptions options = null)
128            => await _frame.WaitForSelectorAsync(
129                _selector,
130                ConvertOptions<FrameWaitForSelectorOptions>(options)).ConfigureAwait(false);
131
132        public Task<IReadOnlyList<IElementHandle>> ElementHandlesAsync()
133            => _frame.QuerySelectorAllAsync(_selector);
134
135        public Task<T> EvaluateAllAsync<T>(string expression, object arg = null)
136            => _frame.EvalOnSelectorAllAsync<T>(_selector, expression, arg);
137
138        public Task<JsonElement?> EvaluateAsync(string expression, object arg = null, LocatorEvaluateOptions options = null)
139            => EvaluateAsync<JsonElement?>(expression, arg, options);
140
141        public Task<T> EvaluateAsync<T>(string expression, object arg = null, LocatorEvaluateOptions options = null)
142            => _frame.EvalOnSelectorAsync<T>(_selector, expression, arg, ConvertOptions<FrameEvalOnSelectorOptions>(options));
143
144        public async Task<IJSHandle> EvaluateHandleAsync(string expression, object arg = null, LocatorEvaluateHandleOptions options = null)
145            => await WithElementAsync(async (e, _) => await e.EvaluateHandleAsync(expression, arg).ConfigureAwait(false), options).ConfigureAwait(false);
146
147        public async Task FillAsync(string value, LocatorFillOptions options = null)
148            => await _frame.FillAsync(_selector, value, ConvertOptions<FrameFillOptions>(options)).ConfigureAwait(false);
149
150        public Task FocusAsync(LocatorFocusOptions options = null)
151            => _frame.FocusAsync(_selector, ConvertOptions<FrameFocusOptions>(options));
152
153        IFrameLocator ILocator.FrameLocator(string selector) =>
154            new FrameLocator(_frame, $"{_selector} >> {selector}");
155
156        public Task<string> GetAttributeAsync(string name, LocatorGetAttributeOptions options = null)
157            => _frame.GetAttributeAsync(_selector, name, ConvertOptions<FrameGetAttributeOptions>(options));
158
159        public Task HoverAsync(LocatorHoverOptions options = null)
160            => _frame.HoverAsync(_selector, ConvertOptions<FrameHoverOptions>(options));
161
162        public Task<string> InnerHTMLAsync(LocatorInnerHTMLOptions options = null)
163            => _frame.InnerHTMLAsync(_selector, ConvertOptions<FrameInnerHTMLOptions>(options));
164
165        public Task<string> InnerTextAsync(LocatorInnerTextOptions options = null)
166            => _frame.InnerTextAsync(_selector, ConvertOptions<FrameInnerTextOptions>(options));
167
168        public Task<string> InputValueAsync(LocatorInputValueOptions options = null)
169            => _frame.InputValueAsync(_selector, ConvertOptions<FrameInputValueOptions>(options));
170
171        public Task<bool> IsCheckedAsync(LocatorIsCheckedOptions options = null)
172            => _frame.IsCheckedAsync(_selector, ConvertOptions<FrameIsCheckedOptions>(options));
173
174        public Task<bool> IsDisabledAsync(LocatorIsDisabledOptions options = null)
175            => _frame.IsDisabledAsync(_selector, ConvertOptions<FrameIsDisabledOptions>(options));
176
177        public Task<bool> IsEditableAsync(LocatorIsEditableOptions options = null)
178            => _frame.IsEditableAsync(_selector, ConvertOptions<FrameIsEditableOptions>(options));
179
180        public Task<bool> IsEnabledAsync(LocatorIsEnabledOptions options = null)
181            => _frame.IsEnabledAsync(_selector, ConvertOptions<FrameIsEnabledOptions>(options));
182
183        public Task<bool> IsHiddenAsync(LocatorIsHiddenOptions options = null)
184            => _frame.IsHiddenAsync(_selector, ConvertOptions<FrameIsHiddenOptions>(options));
185
186        public Task<bool> IsVisibleAsync(LocatorIsVisibleOptions options = null)
187            => _frame.IsVisibleAsync(_selector, ConvertOptions<FrameIsVisibleOptions>(options));
188
189        public ILocator Nth(int index)
190            => new Locator(_frame, $"{_selector} >> nth={index}");
191
192        public Task PressAsync(string key, LocatorPressOptions options = null)
193            => _frame.PressAsync(_selector, key, ConvertOptions<FramePressOptions>(options));
194
195        public Task<byte[]> ScreenshotAsync(LocatorScreenshotOptions options = null)
196            => WithElementAsync(async (h, o) => await h.ScreenshotAsync(ConvertOptions<ElementHandleScreenshotOptions>(o)).ConfigureAwait(false), options);
197
198        public Task ScrollIntoViewIfNeededAsync(LocatorScrollIntoViewIfNeededOptions options = null)
199            => WithElementAsync(async (h, o) => await h.ScrollIntoViewIfNeededAsync(ConvertOptions<ElementHandleScrollIntoViewIfNeededOptions>(o)).ConfigureAwait(false), options);
200
201        public Task<IReadOnlyList<string>> SelectOptionAsync(string values, LocatorSelectOptionOptions options = null)
202            => _frame.SelectOptionAsync(_selector, values, ConvertOptions<FrameSelectOptionOptions>(options));
203
204        public Task<IReadOnlyList<string>> SelectOptionAsync(IElementHandle values, LocatorSelectOptionOptions options = null)
205            => _frame.SelectOptionAsync(_selector, values, ConvertOptions<FrameSelectOptionOptions>(options));
206
207        public Task<IReadOnlyList<string>> SelectOptionAsync(IEnumerable<string> values, LocatorSelectOptionOptions options = null)
208            => _frame.SelectOptionAsync(_selector, values, ConvertOptions<FrameSelectOptionOptions>(options));
209
210        public Task<IReadOnlyList<string>> SelectOptionAsync(SelectOptionValue values, LocatorSelectOptionOptions options = null)
211            => _frame.SelectOptionAsync(_selector, values, ConvertOptions<FrameSelectOptionOptions>(options));
212
213        public Task<IReadOnlyList<string>> SelectOptionAsync(IEnumerable<IElementHandle> values, LocatorSelectOptionOptions options = null)
214            => _frame.SelectOptionAsync(_selector, values, ConvertOptions<FrameSelectOptionOptions>(options));
215
216        public Task<IReadOnlyList<string>> SelectOptionAsync(IEnumerable<SelectOptionValue> values, LocatorSelectOptionOptions options = null)
217            => _frame.SelectOptionAsync(_selector, values, ConvertOptions<FrameSelectOptionOptions>(options));
218
219        public Task SelectTextAsync(LocatorSelectTextOptions options = null)
220            => WithElementAsync((h, o) => h.SelectTextAsync(ConvertOptions<ElementHandleSelectTextOptions>(o)), options);
221
222        public Task SetInputFilesAsync(string files, LocatorSetInputFilesOptions options = null)
223            => _frame.SetInputFilesAsync(_selector, files, ConvertOptions<FrameSetInputFilesOptions>(options));
224
225        public Task SetInputFilesAsync(IEnumerable<string> files, LocatorSetInputFilesOptions options = null)
226            => _frame.SetInputFilesAsync(_selector, files, ConvertOptions<FrameSetInputFilesOptions>(options));
227
228        public Task SetInputFilesAsync(FilePayload files, LocatorSetInputFilesOptions options = null)
229            => _frame.SetInputFilesAsync(_selector, files, ConvertOptions<FrameSetInputFilesOptions>(options));
230
231        public Task SetInputFilesAsync(IEnumerable<FilePayload> files, LocatorSetInputFilesOptions options = null)
232            => _frame.SetInputFilesAsync(_selector, files, ConvertOptions<FrameSetInputFilesOptions>(options));
233
234        public Task TapAsync(LocatorTapOptions options = null)
235            => _frame.TapAsync(_selector, ConvertOptions<FrameTapOptions>(options));
236
237        public Task<string> TextContentAsync(LocatorTextContentOptions options = null)
238            => _frame.TextContentAsync(_selector, ConvertOptions<FrameTextContentOptions>(options));
239
240        public Task TypeAsync(string text, LocatorTypeOptions options = null)
241            => _frame.TypeAsync(_selector, text, ConvertOptions<FrameTypeOptions>(options));
242
243        public Task UncheckAsync(LocatorUncheckOptions options = null)
244            => _frame.UncheckAsync(_selector, ConvertOptions<FrameUncheckOptions>(options));
245
246        ILocator ILocator.Locator(string selector, LocatorLocatorOptions options)
247            => new Locator(_frame, $"{_selector} >> {selector}", options);
248
249        public Task WaitForAsync(LocatorWaitForOptions options = null)
250            => _frame.LocatorWaitForAsync(_selector, ConvertOptions<LocatorWaitForOptions>(options));
251
252        internal Task<FrameExpectResult> ExpectAsync(string expression, FrameExpectOptions options = null)
253            => _frame.ExpectAsync(
254                _selector,
255                expression,
256                options);
257
258        public override string ToString() => "[email protected]" + _selector;
259
260        private T ConvertOptions<T>(object source)
261            where T : class, new()
262        {
263            T target = new();
264            var targetType = target.GetType();
265            if (source != null)
266            {
267                var sourceType = source.GetType();
268                foreach (var sourceProperty in sourceType.GetProperties())
269                {
270                    var targetProperty = targetType.GetProperty(sourceProperty.Name);
271                    if (targetProperty != null)
272                    {
273                        targetProperty.SetValue(target, sourceProperty.GetValue(source));
274                    }
275                }
276            }
277            var strictProperty = targetType.GetProperty("Strict");
278            if (strictProperty != null && strictProperty.GetValue(target) == null)
279            {
280                strictProperty.SetValue(target, true);
281            }
282            return target;
283        }
284
285        private async Task<TResult> WithElementAsync<TOptions, TResult>(Func<IElementHandle, TOptions, Task<TResult>> callback, TOptions options)
286            where TOptions : class
287            where TResult : class
288        {
289            IElementHandle handle = await ElementHandleAsync(ConvertOptions<LocatorElementHandleOptions>(options)).ConfigureAwait(false);
290            try
291            {
292                return await callback(handle, options).ConfigureAwait(false);
293            }
294            finally
295            {
296                await handle.DisposeAsync().ConfigureAwait(false);
297            }
298        }
299
300        private async Task WithElementAsync<TOptions>(Func<IElementHandle, TOptions, Task> callback, TOptions options)
301            where TOptions : class
302        {
303            IElementHandle handle = await ElementHandleAsync(ConvertOptions<LocatorElementHandleOptions>(options)).ConfigureAwait(false);
304            try
305            {
306                await callback(handle, options).ConfigureAwait(false);
307            }
308            finally
309            {
310                await handle.DisposeAsync().ConfigureAwait(false);
311            }
312        }
313
314        public Task HighlightAsync() => _frame.HighlightAsync(_selector);
315    }
316}
317
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)