How to use FocusAsync method of PuppeteerSharp.Frame class

Best Puppeteer-sharp code snippet using PuppeteerSharp.Frame.FocusAsync

Run Puppeteer-sharp automation tests on LambdaTest cloud grid

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

FocusFunction.cs

Source: FocusFunction.cs Github

copy
1using System;
2using System.Linq;
3using System.Threading.Tasks;
4using Ertis.Scraper.Extensions;
5using PuppeteerSharp;
6
7namespace Ertis.Scraper.Interactions
8{
9	public class FocusFunction : FunctionBase, IInteractionFunction
10	{
11		#region Properties
12
13		public override string Name => "focus";
14
15		protected override FunctionParameter[] DefaultParameters
16		{
17			get
18			{
19				return new FunctionParameter[]
20				{
21					new FunctionParameter<string>
22					{
23						Name = "selector"
24					}
25				};
26			}
27		}
28
29		#endregion
30
31		#region Methods
32
33		public async Task ExecuteAsync(Page page)
34		{
35			var selector = this.GetParameterValue<string>("selector");
36			
37			var frame = this.GetParameterValue<string>("frame");
38			if (string.IsNullOrEmpty(frame))
39			{
40				if (selector.StartsWith(XPathSelector.XPathSelectorToken))
41				{
42					var element = await page.QuerySelectorByXPath(selector);
43					if (element != null)
44					{
45						await element.FocusAsync();
46					}
47					else
48					{
49						throw new Exception($"Node not found with '{selector}' selector on focus function");
50					}
51				}
52				else
53				{
54					await page.FocusAsync(selector);	
55				}
56			}
57			else
58			{
59				var currentFrame = page.Frames.FirstOrDefault(x => x.Name == frame);
60				if (currentFrame != null)
61				{
62					if (selector.StartsWith(XPathSelector.XPathSelectorToken))
63					{
64						var element = await currentFrame.QuerySelectorByXPath(selector);
65						if (element != null)
66						{
67							await element.FocusAsync();
68						}
69						else
70						{
71							throw new Exception($"Node not found with '{selector}' selector on focus function");
72						}
73					}
74					else
75					{
76						await currentFrame.FocusAsync(selector);	
77					}
78				}
79				else
80				{
81					throw new Exception($"Frame not found with name '{frame}'");
82				}
83			}
84		}
85
86		#endregion
87	}
88}
Full Screen

Authorization.cs

Source: Authorization.cs Github

copy
1using Newtonsoft.Json;
2using PuppeteerSharp;
3using Serilog;
4using System;
5using System.IO;
6using System.Linq;
7using System.Net;
8using System.Threading;
9using System.Threading.Tasks;
10using System.Diagnostics;
11using static ClassLibrary.Global;
12
13namespace Puppeteer
14{
15    static class Authorization
16    {
17        internal static int DefaultTimeout;
18        internal static async Task<Cookie> GetCookieByAuthorizationAsync(string pathToCookieFile)
19        {
20            /* ОЧЕНЬ ВАЖНО!
21             * В DefaultViewPort стоит параметр null, при котором в развернутом виде КОМПЬЮТЕРНАЯ ВЕРСИЯ,
22             * а в окне достаточно маленького размера у некоторых сайтов МОБИЛЬНАЯ ВЕРСИЯ!
23             * Следовательно, испольнование CSS-селекторов может быть удачным, а может и нет,
24             * в зависимости от размера браузера.
25             * В headless-режиме окно маленького размера. */
26            using (var browser = await PuppeteerSharp.Puppeteer.LaunchAsync(new LaunchOptions
27            {
28                Headless = true,
29                DefaultViewport = null,
30                //Args = PuppeteerSharpLaunchArgs.args
31            }))
32            {
33                Stopwatch timer = new Stopwatch();
34                var p = await GetPage(browser, "about:blank");
35                /* 10 попыток подключения нужны, если сервер плохой, или интернета вдруг нету.*/
36
37                bool success = false;
38                int connectCount = 0;
39                timer.Start();
40                while (connectCount < 10 && !success)
41                {
42                    try
43                    {
44                        await p.GoToAsync("https://dnevnik2.petersburgedu.ru");
45                        success = true;
46                        Log.Information("Подключение к сайту {Site}: успешно!", "https://dnevnik2.petersburgedu.ru");
47                        Log.Information($"{timer.ElapsedMilliseconds}");
48                        timer.Restart();
49                    }
50                    catch (PuppeteerException e)
51                    {
52                        Log.Error(e, "GoToAsync({Site} failed", "https://dnevnik2.petersburgedu.ru");
53                        Log.Information("Подключение к сайту {Site}: Ошибка, повторяю...", "https://dnevnik2.petersburgedu.ru");
54                        Log.Information("Попытка № {attempt}", connectCount + 1);
55                        await System.Threading.Tasks.Task.Delay(3000);
56                        connectCount++;
57                    }
58                }
59
60
61                WaitForSelectorOptions WaitForSelectorTimeout = new WaitForSelectorOptions { Timeout = DefaultTimeout };
62
63                Log.Information($"DefaultTimeout: {p.DefaultTimeout}");
64                Log.Information($"DefaultNavigationTimeout: {p.DefaultNavigationTimeout}");
65
66                const string button = "body > app-root > n3-grid > app-login > div > div.notice > div > app-login-form > div > button";
67                await p.WaitForSelectorAsync(button, WaitForSelectorTimeout);
68                await System.Threading.Tasks.Task.Delay(10000);
69                await p.ClickAsync(button);
70
71                Log.Information("Первый клик {Button}: успешно!", "Войти с ЕСИА");
72                Log.Information($"{timer.ElapsedMilliseconds}");
73                timer.Restart();
74
75                p = await GetPage(browser, "https://esia.gosuslugi.ru");
76                Log.Information($"DefaultTimeout: {p.DefaultTimeout}");
77                Log.Information($"DefaultNavigationTimeout: {p.DefaultNavigationTimeout}");
78
79                // Авторизация
80                await p.WaitForSelectorAsync("#mobileOrEmail", WaitForSelectorTimeout);
81                await p.FocusAsync("#mobileOrEmail");
82                await p.Keyboard.TypeAsync(ConfigJson.Login);
83                Log.Information($"Login: {timer.ElapsedMilliseconds}");
84                timer.Restart();
85
86                await p.WaitForSelectorAsync("#password", WaitForSelectorTimeout);
87                await p.FocusAsync("#password");
88                await p.Keyboard.TypeAsync(ConfigJson.Password);
89                Log.Information($"Password: {timer.ElapsedMilliseconds}");
90                timer.Restart();
91
92                await p.WaitForSelectorAsync("#loginByPwdButton > span", WaitForSelectorTimeout);
93                await p.ClickAsync("#loginByPwdButton > span");
94                Log.Information($"ClickAuthorizationButton: {timer.ElapsedMilliseconds}");
95
96                Log.Information("Авторизация: успешно!");
97                timer.Stop();
98                /* Куки нужны для того, чтобы сайт меня опознал
99                 * при отправке http-запроса на сервер эл. дневника */
100
101                // 10 попыток получения cookie.
102                Cookie cookie;
103                int count = 0;
104                int attempts = (DefaultTimeout / 1000);
105                do
106                {
107                    if (count > attempts) throw new Exception("Cookie X-JMT-Token is not present.");
108                    await System.Threading.Tasks.Task.Delay(1000);
109                    var cookies = await p.GetCookiesAsync();
110                    cookie = cookies.Where(c => c.Name == "X-JWT-Token").Select(c => new Cookie(c.Name, c.Value)).SingleOrDefault();
111                    count++;
112                }
113                while (cookie == null || cookie.Value == "");
114
115                //Здесь и далее безголовый браузер уже не нужен
116                await browser.CloseAsync();
117
118                var cookieAsJson = JsonConvert.SerializeObject(cookie);
119                //await File.WriteAllTextAsync(pathToCookieFile, cookieAsJson);
120                var fm = new ClassLibrary.File_Manager();
121                fm.OpenFile(pathToCookieFile, "Write", cookieAsJson);
122                return cookie;
123            }
124        }
125
126        private static void P_FrameAttached(object sender, FrameEventArgs e)
127        {
128            //Log.Debug("P_FrameAttached sender {@Sender}, e {@e}", sender, e);
129        }
130
131        private static void P_Close(string method)
132        {
133            Log.Debug(method);
134            /*p.Close += (s, e) => P_Close("Close");
135            p.Console += (s, e) => P_Close("Console");
136            p.Dialog += (s, e) => P_Close("Dialog");
137            p.DOMContentLoaded += (s, e) => P_Close("DOMContentLoaded");
138            p.Error += (s, e) => P_Close("Error");
139            p.Load += (s, e) => P_Close("Load");
140            p.Metrics += (s, e) => P_Close("Metrics");
141            p.PageError += (s, e) => P_Close("PageError");
142            p.Popup += (s, e) => P_Close("Popup");
143            p.Request += (s, e) => P_Close("Request");
144            p.RequestFailed += (s, e) => P_Close("RequestFailed");
145            p.RequestFinished += (s, e) => P_Close("RequestFinished");
146            p.Response += (s, e) => P_Close("Response");
147            p.WorkerCreated += (s, e) => P_Close("WorkerCreated");
148            p.WorkerDestroyed += (s, e) => P_Close("WorkerDestroyed");
149            p.FrameAttached += P_FrameAttached;
150            p.FrameDetached += P_FrameAttached;
151            p.FrameNavigated += P_FrameAttached;
152            p.FrameNavigated += P_FrameAttached;*/
153        }
154
155        private static async Task<Page> GetPage(Browser browser, string url)
156        {
157            Page[] pages;
158            do
159            {
160                pages = await browser.PagesAsync();
161                await System.Threading.Tasks.Task.Delay(1000);
162            } while (!pages.Any(p2 => p2.Url.StartsWith(url)));
163            var page = pages.Single(p2 => p2.Url.StartsWith(url));
164            page.DefaultTimeout = DefaultTimeout;
165            page.DefaultNavigationTimeout = DefaultTimeout;
166
167            await page.SetRequestInterceptionAsync(true);
168            page.Request += (sender, e) =>
169            {
170                var cur_type = e.Request.ResourceType;
171                bool isAllowed = true;
172                var disabled_types = PuppeteerSharpLaunchArgs.types;
173                foreach (var d_type in disabled_types)
174                {
175                    if (cur_type == d_type) isAllowed = false;
176                }
177                if (isAllowed)
178                    e.Request.ContinueAsync();
179                else
180                    e.Request.AbortAsync();
181            };
182            return page;
183        }
184    }
185}
186
Full Screen

SelectorException.cs

Source: SelectorException.cs Github

copy
1using System;
2
3namespace PuppeteerSharp
4{
5    /// <summary>
6    /// Exception thrown when an element selector returns null.
7    /// </summary>
8    /// <seealso cref="Extensions.EvaluateFunctionAsync{T}(System.Threading.Tasks.Task{ElementHandle}, string, object[])"/>
9    /// <seealso cref="Frame.SelectAsync(string, string[])"/>
10    /// <seealso cref="Page.ClickAsync(string, Input.ClickOptions)"/>
11    /// <seealso cref="Page.TapAsync(string)"/>
12    /// <seealso cref="Page.HoverAsync(string)"/>
13    /// <seealso cref="Page.FocusAsync(string)"/>
14    /// <seealso cref="Page.SelectAsync(string, string[])"/>
15    [Serializable]
16    public class SelectorException : PuppeteerException
17    {
18        /// <summary>
19        /// Gets the selector.
20        /// </summary>
21        /// <value>The selector.</value>
22        public string Selector { get; }
23
24        /// <summary>
25        /// Initializes a new instance of the <see cref="SelectorException"/> class.
26        /// </summary>
27        /// <param name="message">Message.</param>
28        public SelectorException(string message) : base(message)
29        {
30        }
31        /// <summary>
32        /// Initializes a new instance of the <see cref="SelectorException"/> class.
33        /// </summary>
34        /// <param name="message">Message.</param>
35        /// <param name="selector">Selector.</param>
36        public SelectorException(string message, string selector) : base(message)
37        {
38            Selector = selector;
39        }
40    }
41}
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)