How to use Selectors class of Microsoft.Playwright.Core package

Best Playwright-dotnet code snippet using Microsoft.Playwright.Core.Selectors

Run Playwright-dotnet automation tests on LambdaTest cloud grid

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

BlazorWASMPlaywrightTests.cs

Source: BlazorWASMPlaywrightTests.cs Github

copy
1using Microsoft.Playwright;
2using System.Threading.Tasks;
3using Xunit;
4
5namespace BlazorWASMPlaywright.Tests
6{
7    // https://www.meziantou.net/automated-ui-tests-an-asp-net-core-application-with-playwright-and-xunit.htm
8
9    public class BlazorWASMPlaywrightTests : IClassFixture<BlazorWebAssemblyWebHostFixture<Program>>
10    {
11        private readonly BlazorWebAssemblyWebHostFixture<Program> _server;
12
13        public BlazorWASMPlaywrightTests(BlazorWebAssemblyWebHostFixture<Program> server) => _server = server;
14
15        [Fact]
16        public async Task DisplayHomePage()
17        {
18            var browser = await GetBrowser();
19            var page = await browser.NewPageAsync();
20
21            await page.GotoAsync(_server.RootUri.AbsoluteUri);
22
23            var header = await page.WaitForSelectorAsync("h1");
24            Assert.Equal("Hello, world!", await header.InnerTextAsync());
25
26            await browser.CloseAsync();
27        }
28
29        [Fact]
30        public async Task Counter()
31        {
32            var browser = await GetBrowser();
33            var page = await browser.NewPageAsync();
34
35            await page.GotoAsync(_server.RootUri + "counter", new PageGotoOptions() { WaitUntil = WaitUntilState.NetworkIdle });
36            await page.ClickAsync("#IncrementBtn");
37
38            // Selectors are not only CSS selectors. You can use xpath, css, or text selectors
39            // By default there is a timeout of 30s. If the selector isn't found after the timeout, an exception is thrown.
40            // More about selectors: https://playwright.dev/#version=v1.4.2&path=docs%2Fselectors.md
41            await page.WaitForSelectorAsync("text=Current count: 1");
42
43            await browser.CloseAsync();
44        }
45
46        public static async Task<IBrowser> GetBrowser()
47        {
48            var playwright = await Playwright.CreateAsync();
49            var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions()
50            {
51                Headless = false,
52                SlowMo = 5000
53            });
54
55            return browser;
56        }
57    }
58}
Full Screen

Selectors.cs

Source: Selectors.cs Github

copy
1/*
2 * MIT License
3 *
4 * Copyright (c) Microsoft Corporation.
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in all
14 * copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 * SOFTWARE.
23 */
24
25using System.Threading.Tasks;
26using Microsoft.Playwright.Transport;
27using Microsoft.Playwright.Transport.Channels;
28
29namespace Microsoft.Playwright.Core
30{
31    internal class Selectors : ChannelOwnerBase, IChannelOwner<Selectors>, ISelectors
32    {
33        private readonly SelectorsChannel _channel;
34
35        internal Selectors(IChannelOwner parent, string guid) : base(parent, guid)
36        {
37            _channel = new(guid, parent.Connection, this);
38        }
39
40        ChannelBase IChannelOwner.Channel => _channel;
41
42        IChannel<Selectors> IChannelOwner<Selectors>.Channel => _channel;
43
44        public async Task RegisterAsync(string name, SelectorsRegisterOptions options = default)
45        {
46            options ??= new SelectorsRegisterOptions();
47
48            var script = ScriptsHelper.EvaluationScript(options?.Script, options?.Path);
49            await _channel.RegisterAsync(name, script, options?.ContentScript).ConfigureAwait(false);
50        }
51    }
52}
53
Full Screen

PlaywrightImpl.cs

Source: PlaywrightImpl.cs Github

copy
1/*
2 * MIT License
3 *
4 * Copyright (c) Microsoft Corporation.
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in all
14 * copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 * SOFTWARE.
23 */
24
25using System;
26using System.Collections.Generic;
27using System.Diagnostics.CodeAnalysis;
28using Microsoft.Playwright.Transport;
29using Microsoft.Playwright.Transport.Channels;
30using Microsoft.Playwright.Transport.Protocol;
31
32namespace Microsoft.Playwright.Core
33{
34    [SuppressMessage("Microsoft.Design", "CA1724", Justification = "Playwright is the entrypoint for all languages.")]
35    internal class PlaywrightImpl : ChannelOwnerBase, IPlaywright, IChannelOwner<PlaywrightImpl>
36    {
37        /// <summary>
38        /// Default timeout.
39        /// </summary>
40        public const int DefaultTimeout = 30_000;
41
42        private readonly PlaywrightInitializer _initializer;
43        private readonly PlaywrightChannel _channel;
44        private readonly Connection _connection;
45        private readonly Dictionary<string, BrowserNewContextOptions> _devices = new(StringComparer.InvariantCultureIgnoreCase);
46
47        internal PlaywrightImpl(IChannelOwner parent, string guid, PlaywrightInitializer initializer)
48             : base(parent, guid)
49        {
50            _connection = parent.Connection;
51            _initializer = initializer;
52            _channel = new(guid, parent.Connection, this);
53
54            foreach (var entry in initializer.DeviceDescriptors)
55            {
56                _devices[entry.Name] = entry.Descriptor;
57            }
58            Utils = initializer.Utils;
59
60            _initializer.Chromium.Playwright = this;
61            _initializer.Firefox.Playwright = this;
62            _initializer.Webkit.Playwright = this;
63        }
64
65        ~PlaywrightImpl() => Dispose(false);
66
67        Connection IChannelOwner.Connection => _connection;
68
69        ChannelBase IChannelOwner.Channel => _channel;
70
71        IChannel<PlaywrightImpl> IChannelOwner<PlaywrightImpl>.Channel => _channel;
72
73        public IBrowserType Chromium { get => _initializer.Chromium; set => throw new NotSupportedException(); }
74
75        public IBrowserType Firefox { get => _initializer.Firefox; set => throw new NotSupportedException(); }
76
77        public IBrowserType Webkit { get => _initializer.Webkit; set => throw new NotSupportedException(); }
78
79        public ISelectors Selectors => _initializer.Selectors;
80
81        public IReadOnlyDictionary<string, BrowserNewContextOptions> Devices => _devices;
82
83        internal Connection Connection { get; set; }
84
85        internal Browser PreLaunchedBrowser => _initializer.PreLaunchedBrowser;
86
87        internal LocalUtils Utils { get; set; }
88
89        /// <summary>
90        /// Gets a <see cref="IBrowserType"/>.
91        /// </summary>
92        /// <param name="browserType"><see cref="IBrowserType"/> name. You can get the names from <see cref="global::Microsoft.Playwright.BrowserType"/>.
93        /// e.g.: <see cref="global::Microsoft.Playwright.BrowserType.Chromium"/>,
94        /// <see cref="global::Microsoft.Playwright.BrowserType.Firefox"/> or <see cref="global::Microsoft.Playwright.BrowserType.Webkit"/>.
95        /// </param>
96        public IBrowserType this[string browserType]
97            => browserType?.ToLower() switch
98            {
99                global::Microsoft.Playwright.BrowserType.Chromium => Chromium,
100                global::Microsoft.Playwright.BrowserType.Firefox => Firefox,
101                global::Microsoft.Playwright.BrowserType.Webkit => Webkit,
102                _ => null,
103            };
104
105        public void Dispose()
106        {
107            Dispose(true);
108            GC.SuppressFinalize(this);
109        }
110
111        private void Dispose(bool disposing)
112        {
113            if (!disposing)
114            {
115                return;
116            }
117
118            Connection?.Dispose();
119        }
120    }
121}
122
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

Most used methods in Selectors

Run Selenium Automation Tests on LambdaTest Cloud Grid

Trigger Selenium automation tests on a cloud-based Grid of 3000+ real browsers and operating systems.

Test now for Free
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)