How to use Key method of PuppeteerSharp.Input.Key class

Best Puppeteer-sharp code snippet using PuppeteerSharp.Input.Key.Key

Run Puppeteer-sharp automation tests on LambdaTest cloud grid

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

KeyboardPressFunction.cs

Source: KeyboardPressFunction.cs Github

copy
1using System.Threading.Tasks;
2using PuppeteerSharp;
3using PuppeteerSharp.Input;
4
5namespace Ertis.Scraper.Interactions
6{
7	public class KeyboardPressFunction : FunctionBase, IInteractionFunction
8	{
9		#region Properties
10
11		public override string Name => "keypress";
12
13		protected override FunctionParameter[] DefaultParameters
14		{
15			get
16			{
17				return new FunctionParameter[]
18				{
19					new FunctionParameter<string>
20					{
21						Name = "key"
22					},
23					new FunctionParameter<int?>
24					{
25						Name = "delay"
26					}
27				};
28			}
29		}
30
31		#endregion
32
33		#region Methods
34
35		public async Task ExecuteAsync(Page page)
36		{
37			var key = this.GetParameterValue<string>("key");
38			var delay = this.GetParameterValue<int?>("delay");
39			var pressOptions = delay != null ? new PressOptions { Delay = delay.Value } : null;
40			await page.Keyboard.PressAsync(key, pressOptions);
41		}
42
43		#endregion
44	}
45}
Full Screen

WebScraper.cs

Source: WebScraper.cs Github

copy
1using System;
2using System.Drawing;
3using System.IO;
4using System.Threading.Tasks;
5using PuppeteerSharp;
6using PuppeteerSharp.Input;
7
8namespace ScraperionFramework
9{
10    /// <summary>
11    /// Web scraper class.
12    /// This class handles all interaction with chromium.
13    /// </summary>
14    public class WebScraper : IDisposable
15    {
16        private readonly Browser m_browser;
17        private readonly Page m_page;
18        private decimal m_MouseX = 0;
19        private decimal m_MouseY = 0;
20
21        /// <summary>
22        /// Defualt agent string this library uses. Simulates Chrome installed on windows 10.
23        /// </summary>
24        public static readonly string DefaultAgent =
25            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36";
26
27        /// <summary>
28        /// Constructor.
29        /// </summary>
30        /// <param name="headless">Set to false to show chromium window.</param>
31        /// <param name="agent">Agent to use when accessing pages. Uses DefaultAgent if non is set.</param>
32        public WebScraper(bool headless = true, string agent = "")
33        {
34
35            if (agent == "")
36                agent = DefaultAgent;
37
38
39            var ops = new BrowserFetcherOptions
40            {
41                Path = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\scraperion\\browser"
42            };
43
44            (new BrowserFetcher(ops).DownloadAsync(BrowserFetcher.DefaultRevision)).Wait();
45
46            var browser = Puppeteer.LaunchAsync(new LaunchOptions
47            {
48                Headless = headless,
49                IgnoreHTTPSErrors = true,
50
51            });
52
53            browser.Wait();
54            m_browser = browser.Result;
55
56
57            var page = m_browser.NewPageAsync();
58            page.Wait();
59            m_page = page.Result;
60
61            m_page.Error += (s, e) => {
62                Console.WriteLine("Error:" + e.ToString());
63            };
64
65            m_page.PageError += (s, e) =>
66            {
67                Console.WriteLine("Error:" + e.ToString());
68            };
69
70            m_page.Console += (s, e) => { Console.WriteLine(e.Message.Text); };
71
72            m_page.SetUserAgentAsync(agent).Wait();
73        }
74
75        /// <summary>
76        /// Set username and password to authenticate against web pages with.
77        /// </summary>
78        /// <param name="username">Username to authenticate with</param>
79        /// <param name="password">Password to autrhenticate with.</param>
80        public void SetAuth(string username, string password)
81        {
82            SetAuthAsync(username, password).Wait();
83        }
84
85        private async Task SetAuthAsync(string username, string password)
86        {
87            await m_page.AuthenticateAsync(new Credentials {Username = username, Password = password});
88        }
89
90        /// <summary>
91        /// Sets the view port size of the page.
92        /// </summary>
93        /// <param name="width">Width of the page in pixels.</param>
94        /// <param name="height">Height of page in pixels.</param>
95        public void SetViewPort(int width, int height)
96        {
97            SetViewPortAsync(width, height).Wait();
98        }
99
100        private async Task SetViewPortAsync(int width, int height)
101        {
102            await m_page.SetViewportAsync(new ViewPortOptions
103            {
104                Width = width,
105                Height = height
106            });
107        }
108
109        /// <summary>
110        /// Gets or sets the url the page is currently at.
111        /// </summary>
112        public string Url
113        {
114            get => m_page.Url;
115            set
116            {
117                try
118                {
119                    m_page.GoToAsync(value).Wait();
120                }
121                catch (Exception e)
122                {
123                    Console.WriteLine(e);
124                }
125            }
126        }
127
128        /// <summary>
129        /// Executes a javascript expression on page.
130        /// This is simuilar to typing a command in the java console.
131        /// </summary>
132        /// <param name="script">Expression to run.</param>
133        /// <returns>Json of executed result.</returns>
134        public string Exec(string script)
135        {
136            var result = ExecAsync(script);
137            result.Wait();
138
139            return result.Result;
140        }
141
142        private async Task<string> ExecAsync(string script)
143        {
144
145           var data = await m_page.EvaluateExpressionAsync(script);
146
147            return (string)data.ToString();
148
149        }
150        /// <summary>
151        /// Takes a screenshot of the target page.
152        /// </summary>
153        /// <returns>Bitmap image containing screenshot.</returns>
154        public Bitmap SnapshotBitmap()
155        {
156            var result = SnapshotBitmapAsync();
157            result.Wait();
158            return result.Result;
159        }
160
161        private async Task<Bitmap> SnapshotBitmapAsync()
162        {
163            var data = await m_page.ScreenshotStreamAsync();
164            var image = new Bitmap(data);
165            data.Dispose();
166
167            return image;
168        }
169
170        /// <summary>
171        /// Simulates key presses on page.
172        /// </summary>
173        /// <param name="text">Text to send to page.</param>
174        public void SendKeys(string text)
175        {
176            SendKeysAsync(text).Wait();
177        }
178
179        private async Task SendKeysAsync(string text)
180        {
181            await m_page.Keyboard.TypeAsync(text);
182        }
183
184        /// <summary>
185        /// Simulates moving the mouse on the page.
186        ///
187        /// Note: this does not move the system mouse.
188        /// </summary>
189        /// <param name="x">X coordinates to move mouse to.</param>
190        /// <param name="y">Y coordinates to move mouse to.</param>
191        public void MoveMouse(decimal x, decimal y)
192        {
193            MoveMouseAsync(x, y).Wait();
194        }
195
196        private async Task MoveMouseAsync(decimal x, decimal y)
197        {
198            await m_page.Mouse.MoveAsync(x, y);
199            m_MouseX = x;
200            m_MouseY = y;
201        }
202
203        /// <summary>
204        /// Simulates a mouse click on page.
205        /// </summary>
206        /// <param name="button">Mouse button to simulate.</param>
207        public void MouseClick(MouseButton button)
208        {
209            MouseClickAsync(button).Wait();
210        }
211
212        private async Task MouseClickAsync(MouseButton button)
213        {
214            await m_page.Mouse.ClickAsync(m_MouseX, m_MouseY, new ClickOptions{ Button = button == MouseButton.Left ? PuppeteerSharp.Input.MouseButton.Left : PuppeteerSharp.Input.MouseButton.Right });
215        }
216
217        /// <summary>
218        /// Simulates a mouse up event on page.
219        /// </summary>
220        /// <param name="button">Mouse button to simulate.</param>
221        public void MouseUp(MouseButton button)
222        {
223            MouseUpAsync(button).Wait();
224            
225        }
226
227        private async Task MouseUpAsync(MouseButton button)
228        {
229            await m_page.Mouse.UpAsync(new ClickOptions { Button = button == MouseButton.Left ? PuppeteerSharp.Input.MouseButton.Left : PuppeteerSharp.Input.MouseButton.Right });
230        }
231
232        /// <summary>
233        /// Simulates a mouse down event on page.
234        /// </summary>
235        /// <param name="button">Mouse button to simulate.</param>
236        public void MouseDown(MouseButton button)
237        {
238            MouseDownAsync(button).Wait();
239        }
240
241        private async Task MouseDownAsync(MouseButton button)
242        {
243            await m_page.Mouse.DownAsync(new ClickOptions { Button = button == MouseButton.Left ? PuppeteerSharp.Input.MouseButton.Left : PuppeteerSharp.Input.MouseButton.Right });
244
245        }
246
247        /// <summary>
248        /// Simulates a touch tap on a page.
249        /// </summary>
250        /// <param name="target">Javascript selector for element to tap on.</param>
251        public void TapScreen(string target)
252        {
253            TapScreenAsync(target).Wait();
254        }
255
256        private async Task TapScreenAsync(string target)
257        {
258            await m_page.TapAsync(target);
259        }
260
261        /// <summary>
262        /// Generates a pdf of the page.
263        /// </summary>
264        /// <returns>Stream containing the pdf data.</returns>
265        public Stream CreatePdf()
266        {
267            var data = CreatePdfAsync();
268            data.Wait();
269            return data.Result;
270
271        }
272
273        private async Task<Stream> CreatePdfAsync()
274        {
275            return await m_page.PdfStreamAsync();
276        }
277
278        /// <summary>
279        /// Waits for expression to be to be true.
280        /// </summary>
281        /// <param name="expression">Expression to wait on.</param>
282        public void WaitOnScript(string expression)
283        {
284            WaitOnScriptAsync(expression).Wait();
285        }
286
287        private async Task WaitOnScriptAsync(string expression)
288        {
289            await m_page.WaitForExpressionAsync(expression);
290        }
291
292        /// <summary>
293        /// Selects element on page to have focus.
294        /// </summary>
295        /// <param name="target">Javascript selector to make have focus.</param>
296        public void Focus(string target)
297        {
298            FocusAsync(target).Wait();
299        }
300
301        private async Task FocusAsync(string target)
302        {
303            await m_page.FocusAsync(target);
304        }
305
306        /// <summary>
307        /// Clicks on target element on page.
308        /// </summary>
309        /// <param name="target">Javascript selector of element to click on.</param>
310        public void Click(string target)
311        {
312            ClickAsync(target).Wait();
313        }
314
315        private async Task ClickAsync(string target)
316        {
317            await m_page.ClickAsync(target);
318        }
319
320        /// <summary>
321        /// Html content of page. Useful for scraping the html directly.
322        /// </summary>
323        public string Content
324        {
325            get
326            {
327                var data = m_page.GetContentAsync();
328                data.Wait();
329                return data.Result;
330            }
331            set
332            {
333                var data = m_page.SetContentAsync(value);
334                data.Wait();
335            }
336        }
337
338        /// <inheritdoc />
339        /// <summary>
340        /// Dispose method.
341        /// This will close out chromium session.
342        /// </summary>
343        public void Dispose()
344        {
345            m_browser?.Dispose();
346            m_page?.Dispose();
347        }
348    }
349}
350
Full Screen

PageServer.cs

Source: PageServer.cs Github

copy
1using System;
2using System.Collections.Generic;
3using System.Diagnostics;
4using System.Drawing;
5using System.IO;
6using System.Linq;
7using System.Net.Http;
8using System.Text;
9using System.Text.RegularExpressions;
10using System.Threading.Tasks;
11using IServer;
12using IServer.IPageServer;
13using Newtonsoft.Json.Linq;
14using PuppeteerSharp;
15using PuppeteerSharp.Mobile;
16using Systems;
17
18namespace Server.PageServer
19{
20    public class Jpage
21    {
22        public DateTime regdate { get; set; }
23
24        public Page Page { get; set; }
25    }
26    public class PageServer : IPageServer
27    {
28        private  MainConfig _mainConfig;
29        private OpenCVServer.OpenCVServer cv;
30        public PageServer(MainConfig mainConfig, OpenCVServer.OpenCVServer openCV)
31        {
32            _mainConfig = mainConfig;
33            cv = openCV;
34        }
35        public static Dictionary<string, Page> pagelist = new Dictionary<string, Page>();
36        static readonly object _locker = new object();
37        public  Page AddPage(string phone, Page page)
38        {
39            lock (_locker)
40            {
41                string MaxTab = _mainConfig.MaxTab;
42                if (string.IsNullOrEmpty(MaxTab)) MaxTab = "4";
43                if (!pagelist.ContainsKey(phone))
44                {
45                    if (pagelist.Count < int.Parse(MaxTab))
46                    {
47
48                        pagelist.Add(phone, page);
49                        return page;
50                    }
51
52                }
53                else
54                    return pagelist[phone];
55
56
57            }
58            return null;
59        }
60        public  void Delpage(string phone, Page page)
61        {
62            lock (_locker)
63            {
64                if (pagelist.ContainsKey(phone))
65                {
66                    pagelist.Remove(phone);
67                }
68            }
69        }
70        public  Page GetPage(string Phone)
71        {
72            lock (_locker)
73            {
74                if (!pagelist.ContainsKey(Phone))
75                {
76
77                    return null;
78                }
79                else
80                    return pagelist[Phone];
81            }
82        }
83        public  Page GetPage()
84        {
85            lock (_locker)
86            {
87                System.Threading.Thread.Sleep(500);
88                if (pagelist.Count > 0)
89                    return pagelist.First().Value;
90                else
91                    return null;
92            }
93        }
94        public  int GetPageCount()
95        {
96            lock (_locker)
97            {
98                System.Threading.Thread.Sleep(500);
99
100                return pagelist.Count;
101
102            }
103        }
104        public async Task<bool> BrowserInit()
105        {
106            var browserFetcher = new BrowserFetcher();
107            var aa = await browserFetcher.DownloadAsync("884014");
108            try
109            {
110                var path = aa.ExecutablePath;
111                Bash($"chmod 777 {path}");
112            }
113            catch(Exception e)
114            {
115                Console.WriteLine("执行 CHOMD 777 浏览器地址错位 可以忽略");
116            }
117            return aa.Downloaded;
118        }
119        public void Bash(string cmd)
120        {
121            var escapedArgs = cmd.Replace("\"", "\\\"");
122
123            var process = new Process()
124            {
125                StartInfo = new ProcessStartInfo
126                {
127                    FileName = "/bin/bash",
128                    Arguments = $"-c \"{escapedArgs}\"",
129                    RedirectStandardOutput = true,
130                    UseShellExecute = false,
131                    CreateNoWindow = true,
132                }
133            };
134            process.Start();
135            string result = process.StandardOutput.ReadToEnd();
136            process.WaitForExit();
137        }
138        public async Task<ResultModel<object>> OpenJDTab(int qlkey, string Phone)
139        {
140            DateTime expdate = DateTime.Now;
141
142            ResultModel<object> result = ResultModel<object>.Create(false, "");
143            var qlconfig = _mainConfig.GetConfig(qlkey);
144            if (qlconfig == null)
145            {
146                result.message = "未找到相应的服务器配置。请刷新页面后再试";
147                result.data = new { Status = 404 };
148                return result;
149            }
150            Page page = GetPage();
151            Browser browser = null;
152            if (page == null)
153            {
154                var options = new LaunchOptions
155                {
156                    Args = new string[] { "--no-sandbox", "--disable-setuid-sandbox" },
157                    Headless = true,
158                    DefaultViewport = new ViewPortOptions
159                    {
160                        Width = 375,
161                        Height = 667,
162                        IsMobile = true
163                    }
164
165                };
166                browser = await Puppeteer.LaunchAsync(options);
167            }
168            else
169                browser = page.Browser;
170
171            string MaxTab = _mainConfig.MaxTab;
172            if (string.IsNullOrEmpty(MaxTab)) MaxTab = "4";
173            var Tablist = await browser.PagesAsync();
174            if (Tablist.Length > int.Parse(MaxTab) + 1)
175            {
176                result.message = MaxTab + "个网页资源已经用完。请稍候再试!";
177                result.success = false;
178                return result;
179            }
180           //string Url = "https://plogin.m.jd.com/login/login?appid=300&returnurl=https%3A%2F%2Fwq.jd.com%2Fpassport%2FLoginRedirect%3Fstate%3D2087738584%26returnurl%3Dhttps%253A%252F%252Fhome.m.jd.com%252FmyJd%252Fnewhome.action%253Fsceneval%253D2%2526ufc%253D%2526&source=wq_passport";
181            string Url = "https://bean.m.jd.com/bean/signIndex.action";
182            var context = await browser.CreateIncognitoBrowserContextAsync();
183            page = await context.NewPageAsync();
184            ///屏蔽 WebDriver 检测
185            await page.EvaluateFunctionOnNewDocumentAsync("function(){Object.defineProperty(navigator, 'webdriver', {get: () => undefined})}");
186            DeviceDescriptor deviceOptions = Puppeteer.Devices.GetValueOrDefault(DeviceDescriptorName.IPhone7);
187            await page.EmulateAsync(deviceOptions);
188            await page.GoToAsync(Url);
189            await page.WaitForTimeoutAsync(500);
190            await GetPhoneCode(Phone, page);
191            var seven = await page.EvaluateExpressionAsync("document.querySelectorAll('button[report-eventid=MLoginRegister_SMSReceiveCode]')[0].innerText");
192            await page.ClickAsync("button[report-eventid='MLoginRegister_SMSReceiveCode']");
193            await page.ClickAsync("input[type=checkbox]");
194            await page.WaitForTimeoutAsync(500);
195            string js = "document.body.outerText";
196            var pageouterText = await page.EvaluateExpressionAsync(js);
197            var pagetext = pageouterText.ToString();
198            var data = await getCount(qlkey);
199            if (pagetext.Contains("安全验证") && !pagetext.Contains("验证成功"))
200            {
201                Console.WriteLine(Phone + "安全验证");
202               // await PageClose(Phone);
203                result.data = new { Status = 666,ckcount = data.ckcount, tabcount = data.tabcount };
204                result.message = "出现安全验证,";
205                return result;
206            }
207            if (pagetext.Contains("短信验证码发送次数已达上限"))
208            {
209                await PageClose(Phone);
210                result.data = new { Status = 505, pagetext = pagetext };
211                result.message = "对不起,短信验证码发送次数已达上限,请24小时后再试。";
212                return result;
213            }
214            if (pagetext.Contains("该手机号未注册,将为您直接注册。"))
215            {
216                await PageClose(Phone);
217
218                result.data = new { Status = 501 };
219                result.message = "该手机号未注册";
220                return result;
221            }
222            Console.WriteLine("    手机:" + Phone + " tabe 创建 时间:" + DateTime.Now.ToString());
223            System.Timers.Timer timer = new System.Timers.Timer(60000 * 3);
224            timer.Elapsed += new System.Timers.ElapsedEventHandler(async (s, e) =>
225            {
226                Console.WriteLine("    手机:" + Phone + " tabe 自动回收 时间:" + DateTime.Now.ToString());
227                Delpage(Phone, page);
228                await page.CloseAsync();
229                var oldpage = GetPage();
230                if (oldpage == null)
231                {
232                    await browser.CloseAsync();
233                }
234                timer.Dispose();
235            });
236            timer.AutoReset = false;
237            timer.Start();
238           
239            result.data = new { ckcount = data.ckcount, tabcount = data.tabcount };
240            result.success = true;
241            return result;
242        }
243
244
245        public async Task PageClose(string Phone)
246        {
247            var page = GetPage(Phone);
248            if (page != null)
249            {
250                Delpage(Phone, page);
251                var browser = page.Browser;
252                await page.CloseAsync();
253                var oldpage = GetPage();
254                if (oldpage == null)
255                {
256                    await browser.CloseAsync();
257                }
258            }
259        }
260
261        public async Task ReSendSmSCode(string Phone)
262        {
263            var page = GetPage(Phone);
264            if (page == null) throw new Exception("页面未找到,可能超时回收了.请刷新页面重新登录");
265            await GetPhoneCode(Phone, page);
266        }
267
268        public async Task<ResultModel<object>> VerifyCode(int qlkey, string Phone, string Code)
269        {
270            try
271            {
272                ResultModel<object> result = ResultModel<object>.Create(false, "");
273                var qlconfig = _mainConfig.GetConfig(qlkey);
274                if (qlconfig == null)
275                {
276                    result.message = "未找到相应的服务器配置。请刷新页面后再试";
277                    result.data = new { Status = 404 };
278                    return result;
279                }
280
281                Page page = GetPage(Phone);
282                if (page == null)
283                {
284                    result.message = "未找到当前号码的网页请稍候再试,或者网页超过3分钟已被回收";
285                    result.data = new { Status = 404 };
286                    return result;
287                }
288                await SetCode(Code, page);
289                Console.WriteLine("输入验证码" + Code);
290                Console.WriteLine(page.Url);
291                await page.ClickAsync("a[report-eventid='MLoginRegister_SMSLogin']");
292                //  
293                await page.WaitForTimeoutAsync(2500);
294                string js = "document.body.outerText";
295                var pageouterText = await page.EvaluateExpressionAsync(js);
296                var pagetext = pageouterText.ToString();
297                // Console.WriteLine(pagetext.ToString());
298                if (pagetext.Contains("验证码输入错误"))
299                {
300                    result.message = "验证码输入错误";
301                    return result;
302                }
303                if (pagetext.Contains("验证码错误多次,请重新获取"))
304                {
305                    await PageClose(Phone);
306                    result.data = new { Status = 501 };
307                    result.message = "验证码错误多次,请过三分钟之后再来。";
308                    return result;
309                }
310                if (pagetext.Contains("该手机号未注册,将为您直接注册。"))
311                {
312                    await PageClose(Phone);
313
314                    result.data = new { Status = 501 };
315                    result.message = "该手机号未注册";
316                    return result;
317                }
318
319                await page.WaitForTimeoutAsync(2500);
320                var cookies = await page.GetCookiesAsync();
321                var CKkey = cookies.FirstOrDefault(x => x.Name == "pt_key");
322                var CKpin = cookies.FirstOrDefault(x => x.Name == "pt_pin");
323                if (CKkey == null || CKpin == null)
324                {
325                    await PageClose(Phone);
326                    result.message = "获取Cookie失败,请重试";
327                    result.data = new { Status = 404 };
328                    return result;
329                }
330                int MAXCount = qlconfig.QL_CAPACITY;
331                var CCookie = CKkey.Name + "=" + CKkey.Value + ";" + CKpin.Name + "=" + CKpin.Value + ";";
332                var Nickname = "";
333                Nickname = await GetNickname(CCookie);
334                JArray data = await qlconfig.GetEnv();
335                var env = data.FirstOrDefault(x => x["value"].ToString().Contains("pt_pin=" + CKpin.Value + ";"));
336                var QLCount = data.Count;
337               
338                string QLId = "";
339                string timestamp = "";
340                if (env == null)
341                {
342                    if (QLCount >= MAXCount)
343                    {
344                        result.message = "你来晚了,没有多余的位置了";
345                        result.data = new { Status = 501 };
346                        return result;
347                    }
348                    
349                    var addresult = await qlconfig.AddEnv(CCookie, Nickname);
350                    JObject addUser = (JObject)addresult.data[0];
351                    QLId = addUser["_id"].ToString();
352                    timestamp = addUser["timestamp"].ToString();
353                }
354                else
355                {
356                    QLId = env["_id"].ToString();
357                    if(env["remarks"] != null)
358                        Nickname = env["remarks"].ToString();
359                    
360
361                    var upresult = await qlconfig.UpdateEnv(CCookie, QLId, Nickname);
362                    timestamp = upresult.data["timestamp"].ToString();
363                }
364                var qin = await getCount(qlkey);
365                await PageClose(Phone);
366                result.success = true;
367                result.data = new { qlid = QLId, nickname = Nickname, timestamp = timestamp, remarks = Nickname, qlkey = qlconfig.QLkey, ckcount = qin.ckcount, tabcount = qin.tabcount };
368                return result;
369            }catch(Exception e)
370            {
371                Console.WriteLine(e.ToString());
372                throw e;
373            }
374           
375        }
376        public  async Task<(int ckcount, int tabcount)> getCount(int qlkey)
377        {
378            var config = _mainConfig.GetConfig(qlkey);
379            var qlcount = await config.GetEnvsCount();
380            var ckcount = config.QL_CAPACITY - qlcount;
381            string MaxTab = _mainConfig.MaxTab;
382            var intabcount = GetPageCount();
383            int tabcount = int.Parse(MaxTab) - intabcount;
384            return (ckcount, tabcount);
385        }
386        private  async Task Setphone(string phone, Page page)
387        {
388            string jq = @"document.querySelectorAll('input[report-eventid=MLoginRegister_SMSPhoneInput]')[0].value='';";
389            await page.EvaluateExpressionAsync(jq);
390            System.Threading.Thread.Sleep(500);
391            await page.TypeAsync("input[report-eventid=MLoginRegister_SMSPhoneInput]", phone);
392            System.Threading.Thread.Sleep(500);
393        }
394        private  async Task<bool> GetPhoneCode(string Phone, Page page)
395        {
396            page = AddPage(Phone, page);
397            await Setphone(Phone, page);
398            var CodeBtn = await page.XPathAsync("//button[@report-eventid='MLoginRegister_SMSReceiveCode']");
399            var CodeProperties = await CodeBtn[0].GetPropertiesAsync();
400            var CodeBtnClasses = CodeProperties["_prevClass"].ToString().Split(" ");
401            bool canSendCode = CodeBtnClasses.Contains("active");
402            if (canSendCode)
403            {
404                return true;
405            }
406            else
407            {
408                await page.ReloadAsync();
409                System.Threading.Thread.Sleep(500);
410                return await GetPhoneCode(Phone, page);
411            }
412        }
413        private  long GetTime()
414        {
415            TimeSpan ts = DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1);//ToUniversalTime()转换为标准时区的时间,去掉的话直接就用北京时间
416            return (long)ts.TotalSeconds;
417        }
418        private  async Task<string> GetNickname(string cookie)
419        {
420            try
421            {
422                var url = @"https://me-api.jd.com/user_new/info/GetJDUserInfoUnion?orgFlag=JD_PinGou_New&callSource=mainorder&channel=4&isHomewhite=0&sceneval=2&_=" + GetTime() + "&sceneval=2&g_login_type=1&g_ty=ls";
423                using (HttpClient client = new HttpClient())
424                {
425
426                    client.DefaultRequestHeaders.Add("Cookie", cookie);
427                    client.DefaultRequestHeaders.Add("Referer", "https://home.m.jd.com/myJd/newhome.action");
428                    client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36");
429                    client.DefaultRequestHeaders.Add("Host", "me-api.jd.com");
430                    var result = await client.GetAsync(url);
431                    string resultContent = result.Content.ReadAsStringAsync().Result;
432                    //  Console.WriteLine(resultContent);
433                    JObject j = JObject.Parse(resultContent);
434                    // data?.userInfo.baseInfo.nickname
435                    return j["data"]["userInfo"]["baseInfo"]["nickname"].ToString();
436                }
437            }
438            catch(Exception e)
439            {
440                return "未知";
441            }
442            
443
444        }
445
446        private static async Task SetCode(string Code, Page page)
447        {
448            await page.ClickAsync("#authcode", new PuppeteerSharp.Input.ClickOptions { ClickCount = 3 });
449            System.Threading.Thread.Sleep(500);
450            await page.TypeAsync("#authcode", Code);
451            System.Threading.Thread.Sleep(500);
452
453        }
454
455        public async Task<ResultModel<object>> AutoCaptcha(string Phone)
456        {
457            Console.WriteLine(Phone + "安全验证破解");
458            var page = GetPage(Phone);
459            var cpc_img = await page.QuerySelectorAsync("#cpc_img");
460            var cpc_imgheader = await cpc_img.GetPropertyAsync("src");
461            var cpc_imgsrc = await cpc_imgheader.JsonValueAsync();
462            var small_img = await page.QuerySelectorAsync("#small_img");
463            var small_imgheader = await small_img.GetPropertyAsync("src");
464            var small_imgsrc = await small_imgheader.JsonValueAsync();
465            string pattern = @"data:image.*base64,(.*)";
466            Match m = Regex.Match(cpc_imgsrc.ToString(), pattern);
467            var cpc_imgbase64 = m.Groups[1].ToString();
468            Match m2 = Regex.Match(small_imgsrc.ToString(), pattern);
469            var small_imgbase64 = m2.Groups[1].ToString();
470            byte[] cpc_imgBytes = Convert.FromBase64String(cpc_imgbase64);
471            byte[] small_imgbaseBytes = Convert.FromBase64String(small_imgbase64);
472            Stream cpcstream = new MemoryStream(cpc_imgBytes);
473            Stream smallstream = new MemoryStream(small_imgbaseBytes);
474            var cpcmap = new Bitmap(new Bitmap(cpcstream));
475            var smallmap = new Bitmap(new Bitmap(smallstream));
476            var Rsct = cv.getOffsetX(cpcmap, smallmap);
477            cpcmap.Dispose();
478            cpcstream.Close();
479            smallstream.Close();
480            smallmap.Dispose();
481            var list = cv.GetPoints2(Rsct);
482            var slider = await page.WaitForXPathAsync("//div[@class='sp_msg']/img");
483            var box = await slider.BoundingBoxAsync();
484            await page.Mouse.MoveAsync(box.X, box.Y);
485            await page.Mouse.DownAsync();
486            Random r = new Random(Guid.NewGuid().GetHashCode());
487            var Steps = r.Next(5, 15);
488            foreach (var item in list)
489            {
490                await page.Mouse.MoveAsync(item.X, box.Y, new PuppeteerSharp.Input.MoveOptions { Steps = Steps });
491
492            }
493            await page.Mouse.UpAsync();
494            await page.WaitForTimeoutAsync(1000);
495            var html = await page.GetContentAsync();
496            
497            ResultModel<object> result = ResultModel<object>.Create(false, "");
498            if (html.Contains("重新获取"))
499            {
500                Console.WriteLine("验证成功");
501                result.success = true;
502            }
503            else
504            {
505                if (html.Contains("短信验证码发送次数已达上限"))
506                {
507                    await PageClose(Phone);
508                    result.data = new { Status = 505 };
509                    result.message = "对不起,短信验证码发送次数已达上限,请24小时后再试。";
510                    return result;
511                }
512                if (html.Contains("该手机号未注册,将为您直接注册。"))
513                {
514                    await PageClose(Phone);
515
516                    result.data = new { Status = 505 };
517                    result.message = "该手机号未注册";
518                    return result;
519                }
520                Console.WriteLine("验证失败");
521                result.data = new { Status = 666 };
522            }
523            return result;
524        }
525    }
526}
527
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

Trigger Key code on LambdaTest Cloud Grid

Execute automation tests with Key on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

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)