Best Puppeteer-sharp code snippet using PuppeteerSharp.Input.Key.string
PageServer.cs
Source:PageServer.cs
...29 {30 _mainConfig = mainConfig;31 cv = openCV;32 }33 public static Dictionary<string, Page> pagelist = new Dictionary<string, Page>();34 static readonly object _locker = new object();35 public Page AddPage(string phone, Page page)36 {37 lock (_locker)38 {39 string MaxTab = _mainConfig.MaxTab;40 if (string.IsNullOrEmpty(MaxTab)) MaxTab = "4";41 if (!pagelist.ContainsKey(phone))42 {43 if (pagelist.Count < int.Parse(MaxTab))44 {45 pagelist.Add(phone, page);46 return page;47 }48 }49 else50 return pagelist[phone];51 }52 return null;53 }54 public void Delpage(string phone, Page page)55 {56 lock (_locker)57 {58 if (pagelist.ContainsKey(phone))59 {60 pagelist.Remove(phone);61 }62 }63 }64 public Page GetPage(string Phone)65 {66 lock (_locker)67 {68 if (!pagelist.ContainsKey(Phone))69 {70 return null;71 }72 else73 return pagelist[Phone];74 }75 }76 public Page GetPage()77 {78 lock (_locker)79 {80 System.Threading.Thread.Sleep(500);81 if (pagelist.Count > 0)82 return pagelist.First().Value;83 else84 return null;85 }86 }87 public int GetPageCount()88 {89 lock (_locker)90 {91 System.Threading.Thread.Sleep(500);92 return pagelist.Count;93 }94 }95 public async Task<bool> BrowserInit()96 {97 var browserFetcher = new BrowserFetcher();98 var aa = await browserFetcher.DownloadAsync("884014");99 try100 {101 var path = aa.ExecutablePath;102 Bash($"chmod 777 {path}");103 }104 catch(Exception e)105 {106 Console.WriteLine("æ§è¡ CHOMD 777 æµè§å¨å°åéä½ å¯ä»¥å¿½ç¥");107 }108 return aa.Downloaded;109 }110 public void Bash(string cmd)111 {112 var escapedArgs = cmd.Replace("\"", "\\\"");113 var process = new Process()114 {115 StartInfo = new ProcessStartInfo116 {117 FileName = "/bin/bash",118 Arguments = $"-c \"{escapedArgs}\"",119 RedirectStandardOutput = true,120 UseShellExecute = false,121 CreateNoWindow = true,122 }123 };124 process.Start();125 string result = process.StandardOutput.ReadToEnd();126 process.WaitForExit();127 }128 public async Task<ResultModel<object>> OpenJDTab(int qlkey, string Phone)129 {130 DateTime expdate = DateTime.Now;131 ResultModel<object> result = ResultModel<object>.Create(false, "");132 var qlconfig = _mainConfig.GetConfig(qlkey);133 if (qlconfig == null)134 {135 result.message = "æªæ¾å°ç¸åºçæå¡å¨é
ç½®ã请å·æ°é¡µé¢ååè¯";136 result.data = new { Status = 404 };137 return result;138 }139 Page page = GetPage();140 Browser browser = null;141 if (page == null)142 {143 var options = new LaunchOptions144 {145 Args = new string[] { "--no-sandbox", "--disable-setuid-sandbox" },146 Headless = true,147 DefaultViewport = new ViewPortOptions148 {149 Width = 375,150 Height = 667,151 IsMobile = true152 }153 };154 browser = await Puppeteer.LaunchAsync(options);155 }156 else157 browser = page.Browser;158 string MaxTab = _mainConfig.MaxTab;159 if (string.IsNullOrEmpty(MaxTab)) MaxTab = "4";160 var Tablist = await browser.PagesAsync();161 if (Tablist.Length > int.Parse(MaxTab) + 1)162 {163 result.message = MaxTab + "个ç½é¡µèµæºå·²ç»ç¨å®ã请ç¨ååè¯!";164 result.success = false;165 return result;166 }167 //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";168 string Url = "https://bean.m.jd.com/bean/signIndex.action";169 var context = await browser.CreateIncognitoBrowserContextAsync();170 page = await context.NewPageAsync();171 ///å±è½ WebDriver æ£æµ172 await page.EvaluateFunctionOnNewDocumentAsync("function(){Object.defineProperty(navigator, 'webdriver', {get: () => undefined})}");173 DeviceDescriptor deviceOptions = Puppeteer.Devices.GetValueOrDefault(DeviceDescriptorName.IPhone7);174 await page.EmulateAsync(deviceOptions);175 await page.GoToAsync(Url);176 await page.WaitForTimeoutAsync(500);177 await GetPhoneCode(Phone, page);178 var seven = await page.EvaluateExpressionAsync("document.querySelectorAll('button[report-eventid=MLoginRegister_SMSReceiveCode]')[0].innerText");179 await page.ClickAsync("button[report-eventid='MLoginRegister_SMSReceiveCode']");180 await page.ClickAsync("input[type=checkbox]");181 await page.WaitForTimeoutAsync(500);182 string js = "document.body.outerText";183 var pageouterText = await page.EvaluateExpressionAsync(js);184 var pagetext = pageouterText.ToString();185 var data = await getCount(qlkey);186 if (pagetext.Contains("å®å
¨éªè¯") && !pagetext.Contains("éªè¯æå"))187 {188 Console.WriteLine(Phone + "å®å
¨éªè¯");189 // await PageClose(Phone);190 result.data = new { Status = 666,ckcount = data.ckcount, tabcount = data.tabcount };191 result.message = "åºç°å®å
¨éªè¯,";192 return result;193 }194 if (pagetext.Contains("çä¿¡éªè¯ç åé次æ°å·²è¾¾ä¸é"))195 {196 await PageClose(Phone);197 result.data = new { Status = 505, pagetext = pagetext };198 result.message = "对ä¸èµ·ï¼çä¿¡éªè¯ç åé次æ°å·²è¾¾ä¸éï¼è¯·24å°æ¶ååè¯ã";199 return result;200 }201 if (pagetext.Contains("该ææºå·æªæ³¨åï¼å°ä¸ºæ¨ç´æ¥æ³¨åã"))202 {203 await PageClose(Phone);204 result.data = new { Status = 501 };205 result.message = "该ææºå·æªæ³¨å";206 return result;207 }208 Console.WriteLine(" ææºï¼" + Phone + " tabe å建 æ¶é´:" + DateTime.Now.ToString());209 System.Timers.Timer timer = new System.Timers.Timer(60000 * 3);210 timer.Elapsed += new System.Timers.ElapsedEventHandler(async (s, e) =>211 {212 Console.WriteLine(" ææºï¼" + Phone + " tabe èªå¨åæ¶ æ¶é´:" + DateTime.Now.ToString());213 Delpage(Phone, page);214 await page.CloseAsync();215 var oldpage = GetPage();216 if (oldpage == null)217 {218 await browser.CloseAsync();219 }220 timer.Dispose();221 });222 timer.AutoReset = false;223 timer.Start();224 225 result.data = new { ckcount = data.ckcount, tabcount = data.tabcount };226 result.success = true;227 return result;228 }229 public async Task PageClose(string Phone)230 {231 var page = GetPage(Phone);232 if (page != null)233 {234 Delpage(Phone, page);235 var browser = page.Browser;236 await page.CloseAsync();237 var oldpage = GetPage();238 if (oldpage == null)239 {240 await browser.CloseAsync();241 }242 }243 }244 public async Task ReSendSmSCode(string Phone)245 {246 var page = GetPage(Phone);247 if (page == null) throw new Exception("页é¢æªæ¾å°,å¯è½è¶
æ¶åæ¶äº.请å·æ°é¡µé¢éæ°ç»å½");248 await GetPhoneCode(Phone, page);249 }250 public async Task<ResultModel<object>> VerifyCode(int qlkey, string Phone, string Code)251 {252 try253 {254 ResultModel<object> result = ResultModel<object>.Create(false, "");255 var qlconfig = _mainConfig.GetConfig(qlkey);256 if (qlconfig == null)257 {258 result.message = "æªæ¾å°ç¸åºçæå¡å¨é
ç½®ã请å·æ°é¡µé¢ååè¯";259 result.data = new { Status = 404 };260 return result;261 }262 Page page = GetPage(Phone);263 if (page == null)264 {265 result.message = "æªæ¾å°å½åå·ç çç½é¡µè¯·ç¨ååè¯,æè
ç½é¡µè¶
è¿3åé已被åæ¶";266 result.data = new { Status = 404 };267 return result;268 }269 await SetCode(Code, page);270 Console.WriteLine("è¾å
¥éªè¯ç " + Code);271 Console.WriteLine(page.Url);272 await page.ClickAsync("a[report-eventid='MLoginRegister_SMSLogin']");273 // 274 await page.WaitForTimeoutAsync(2500);275 string js = "document.body.outerText";276 var pageouterText = await page.EvaluateExpressionAsync(js);277 var pagetext = pageouterText.ToString();278 // Console.WriteLine(pagetext.ToString());279 if (pagetext.Contains("éªè¯ç è¾å
¥é误"))280 {281 result.message = "éªè¯ç è¾å
¥é误";282 return result;283 }284 if (pagetext.Contains("éªè¯ç é误å¤æ¬¡ï¼è¯·éæ°è·å"))285 {286 await PageClose(Phone);287 result.data = new { Status = 501 };288 result.message = "éªè¯ç é误å¤æ¬¡,请è¿ä¸åéä¹ååæ¥ã";289 return result;290 }291 if (pagetext.Contains("该ææºå·æªæ³¨åï¼å°ä¸ºæ¨ç´æ¥æ³¨åã"))292 {293 await PageClose(Phone);294 result.data = new { Status = 501 };295 result.message = "该ææºå·æªæ³¨å";296 return result;297 }298 await page.WaitForTimeoutAsync(2500);299 var cookies = await page.GetCookiesAsync();300 var CKkey = cookies.FirstOrDefault(x => x.Name == "pt_key");301 var CKpin = cookies.FirstOrDefault(x => x.Name == "pt_pin");302 if (CKkey == null || CKpin == null)303 {304 await PageClose(Phone);305 result.message = "è·åCookie失败ï¼è¯·éè¯";306 result.data = new { Status = 404 };307 return result;308 }309 int MAXCount = qlconfig.QL_CAPACITY;310 var CCookie = CKkey.Name + "=" + CKkey.Value + ";" + CKpin.Name + "=" + CKpin.Value + ";";311 var Nickname = "";312 Nickname = await GetNickname(CCookie);313 JArray data = await qlconfig.GetEnv();314 var env = data.FirstOrDefault(x => x["value"].ToString().Contains("pt_pin=" + CKpin.Value + ";"));315 var QLCount = data.Count;316 317 string QLId = "";318 string timestamp = "";319 if (env == null)320 {321 if (QLCount >= MAXCount)322 {323 result.message = "ä½ æ¥æäºï¼æ²¡æå¤ä½çä½ç½®äº";324 result.data = new { Status = 501 };325 return result;326 }327 328 var addresult = await qlconfig.AddEnv(CCookie, Nickname);329 JObject addUser = (JObject)addresult.data[0];330 QLId = addUser["_id"].ToString();331 timestamp = addUser["timestamp"].ToString();332 }333 else334 {335 QLId = env["_id"].ToString();336 if(env["remarks"] != null)337 Nickname = env["remarks"].ToString();338 339 var upresult = await qlconfig.UpdateEnv(CCookie, QLId, Nickname);340 timestamp = upresult.data["timestamp"].ToString();341 }342 var qin = await getCount(qlkey);343 await PageClose(Phone);344 result.success = true;345 result.data = new { qlid = QLId, nickname = Nickname, timestamp = timestamp, remarks = Nickname, qlkey = qlconfig.QLkey, ckcount = qin.ckcount, tabcount = qin.tabcount };346 return result;347 }catch(Exception e)348 {349 Console.WriteLine(e.ToString());350 throw e;351 }352 353 }354 public async Task<(int ckcount, int tabcount)> getCount(int qlkey)355 {356 var config = _mainConfig.GetConfig(qlkey);357 var qlcount = await config.GetEnvsCount();358 var ckcount = config.QL_CAPACITY - qlcount;359 string MaxTab = _mainConfig.MaxTab;360 var intabcount = GetPageCount();361 int tabcount = int.Parse(MaxTab) - intabcount;362 return (ckcount, tabcount);363 }364 private async Task Setphone(string phone, Page page)365 {366 string jq = @"document.querySelectorAll('input[report-eventid=MLoginRegister_SMSPhoneInput]')[0].value='';";367 await page.EvaluateExpressionAsync(jq);368 System.Threading.Thread.Sleep(500);369 await page.TypeAsync("input[report-eventid=MLoginRegister_SMSPhoneInput]", phone);370 System.Threading.Thread.Sleep(500);371 }372 private async Task<bool> GetPhoneCode(string Phone, Page page)373 {374 page = AddPage(Phone, page);375 await Setphone(Phone, page);376 var CodeBtn = await page.XPathAsync("//button[@report-eventid='MLoginRegister_SMSReceiveCode']");377 var CodeProperties = await CodeBtn[0].GetPropertiesAsync();378 var CodeBtnClasses = CodeProperties["_prevClass"].ToString().Split(" ");379 bool canSendCode = CodeBtnClasses.Contains("active");380 if (canSendCode)381 {382 return true;383 }384 else385 {386 await page.ReloadAsync();387 System.Threading.Thread.Sleep(500);388 return await GetPhoneCode(Phone, page);389 }390 }391 private long GetTime()392 {393 TimeSpan ts = DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1);//ToUniversalTime()转æ¢ä¸ºæ åæ¶åºçæ¶é´,å»æçè¯ç´æ¥å°±ç¨å京æ¶é´394 return (long)ts.TotalSeconds;395 }396 private async Task<string> GetNickname(string cookie)397 {398 try399 {400 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";401 using (HttpClient client = new HttpClient())402 {403 client.DefaultRequestHeaders.Add("Cookie", cookie);404 client.DefaultRequestHeaders.Add("Referer", "https://home.m.jd.com/myJd/newhome.action");405 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");406 client.DefaultRequestHeaders.Add("Host", "me-api.jd.com");407 var result = await client.GetAsync(url);408 string resultContent = result.Content.ReadAsStringAsync().Result;409 // Console.WriteLine(resultContent);410 JObject j = JObject.Parse(resultContent);411 // data?.userInfo.baseInfo.nickname412 return j["data"]["userInfo"]["baseInfo"]["nickname"].ToString();413 }414 }415 catch(Exception e)416 {417 return "æªç¥";418 }419 420 }421 private static async Task SetCode(string Code, Page page)422 {423 await page.ClickAsync("#authcode", new PuppeteerSharp.Input.ClickOptions { ClickCount = 3 });424 System.Threading.Thread.Sleep(500);425 await page.TypeAsync("#authcode", Code);426 System.Threading.Thread.Sleep(500);427 }428 public async Task<ResultModel<object>> AutoCaptcha(string Phone)429 {430 Console.WriteLine(Phone + "å®å
¨éªè¯ç ´è§£");431 var page = GetPage(Phone);432 var cpc_img = await page.QuerySelectorAsync("#cpc_img");433 var cpc_imgheader = await cpc_img.GetPropertyAsync("src");434 var cpc_imgsrc = await cpc_imgheader.JsonValueAsync();435 var small_img = await page.QuerySelectorAsync("#small_img");436 var small_imgheader = await small_img.GetPropertyAsync("src");437 var small_imgsrc = await small_imgheader.JsonValueAsync();438 string pattern = @"data:image.*base64,(.*)";439 Match m = Regex.Match(cpc_imgsrc.ToString(), pattern);440 var cpc_imgbase64 = m.Groups[1].ToString();441 Match m2 = Regex.Match(small_imgsrc.ToString(), pattern);442 var small_imgbase64 = m2.Groups[1].ToString();443 byte[] cpc_imgBytes = Convert.FromBase64String(cpc_imgbase64);444 byte[] small_imgbaseBytes = Convert.FromBase64String(small_imgbase64);445 Stream cpcstream = new MemoryStream(cpc_imgBytes);446 Stream smallstream = new MemoryStream(small_imgbaseBytes);447 var cpcmap = new Bitmap(new Bitmap(cpcstream));448 var smallmap = new Bitmap(new Bitmap(smallstream));449 var Rsct = cv.getOffsetX(cpcmap, smallmap);450 cpcmap.Dispose();451 cpcstream.Close();452 smallstream.Close();...
Index.cshtml.cs
Source:Index.cshtml.cs
...29 {30 31 32 33 string phone = "13113075869";34 await "https://upay.10010.com/npfwap/NpfMob/usernumber/get4gInfo"35 .WithHeaders(new { Referer = "https://upay.10010.com/jf_wxgz" })36 .WithCookies(out var cookies)37 .PostUrlEncodedAsync(new { phoneNo = phone });38 var offeRateOrder = await "https://upay.10010.com/npfwap/NpfMobAppQuery/feeSearch/OfferateOrder"39 .WithHeaders(new { Referer = "https://upay.10010.com/jf_wxgz" })40 .WithCookies(cookies).PostAsync()41 .ReceiveString();42 var needCodeResponse = await "https://upay.10010.com/npfwap/NpfMob/needCode?channelType=307&channelKey=wxgz"43 .WithHeaders(new { Referer = "https://upay.10010.com/jf_wxgz" })44 .WithCookies(cookies)45 .GetAsync();46 for (int i = 0; i < needCodeResponse.Cookies.Count; i++)47 {48 cookies.AddOrReplace(needCodeResponse.Cookies[i]);49 }50 var nedCode =await needCodeResponse.GetStringAsync();51 var aliToken = ""; 52 var aliSessionId = "";53 var aliSig = "";54 if (nedCode.Trim() == "yes")55 {56 var version = await new BrowserFetcher().DownloadAsync(615489);57 var browser = await Puppeteer.LaunchAsync(new LaunchOptions58 {59 Headless = false,60 Args = new string[]61 {62 "--no-sandbox",63 "--disable-setuid-sandbox"64 },65 ExecutablePath = version.ExecutablePath,66 Devtools = true67 });68 var page = await browser.NewPageAsync();69 await page.GoToAsync("https://localhost:5001/VerificationCode/index");70 await page.EvaluateFunctionHandleAsync("() =>{Object.defineProperty(navigator, 'webdriver', {get: () => false});}");71 await page.EvaluateFunctionOnNewDocumentAsync("() =>{ window.navigator.chrome = { runtime: {}, }; }");72 await page.EvaluateFunctionOnNewDocumentAsync("() =>{ Object.defineProperty(navigator, 'languages', { get: () => ['en-US', 'en'] }); }");73 await page.EvaluateFunctionOnNewDocumentAsync("() =>{ Object.defineProperty(navigator, 'plugins', { get: () => [1, 2, 3, 4, 5,6], }); }");74 Console.WriteLine(await page.EvaluateExpressionAsync("navigator.webdriver"));75 var slideBtn = await page.WaitForSelectorAsync("#nc_1_n1t", new WaitForSelectorOptions { Timeout = 3 * 1000 });76 var rect = await slideBtn.BoundingBoxAsync();77 var left = rect.X + 10;78 var top = rect.Y + 10;79 var mouse = page.Mouse;80 await mouse.MoveAsync(left, top);81 await page.Touchscreen.TapAsync(left, top);82 await mouse.DownAsync();83 var startTime = DateTime.Now;84 await mouse.MoveAsync(left + 800, top, new PuppeteerSharp.Input.MoveOptions { Steps = 30 });85 await page.Touchscreen.TapAsync(left + 800, top);86 Console.WriteLine(DateTime.Now - startTime);87 await mouse.UpAsync();88 var success = await page.WaitForSelectorAsync(".yes", new WaitForSelectorOptions { Timeout = 3000 });89 string content = await page.GetContentAsync();90 91 var parser = new HtmlParser();92 var document = await parser.ParseDocumentAsync(content);93 aliToken = (document.GetElementById("aliToken") as IHtmlInputElement).GetAttribute("sms");94 aliSessionId = (document.GetElementById("aliSessionId") as IHtmlInputElement).GetAttribute("sms");95 aliSig = (document.GetElementById("aliSig") as IHtmlInputElement).GetAttribute("sms");96 }97 var response = await "https://upay.10010.com/npfwap/NpfMob/needdubbo/needDubboCheck?phoneNo=13113075869&amountMoney=200&channelKey=wxgz"98 .WithHeaders(new { Referer = "https://upay.10010.com/jf_wxgz" })99 .WithCookies(cookies)100 .GetStringAsync();101 var dubbocheck = JsonConvert.DeserializeObject<NeedDubboCheckInput>(response);102 var action = await "https://upay.10010.com/npfwap/NpfMob/mobWapBankCharge/bankChargePayChannel.action"103 .WithHeaders(new { Referer = "https://upay.10010.com/jf_wxgz" })104 .WithCookies(cookies)105 .PostUrlEncodedAsync(new106 {107 phoneNo = phone,108 areaCode = "",109 provinceCode = "051",110 cityCode = "580",111 bussineTypeInput = "0",112 payAmount = "200",113 numberType = "",114 channelType = "307",115 channelKey = "wxgz",116 bussineType = "06",117 netAccount = "",118 browserVersion = "",119 ticketNew = "ticket",120 token = aliToken,121 sessionid = aliSessionId,122 sig = aliSig,123 joinSign = "",124 username = "",125 state = dubbocheck.Secstate126 }).ReceiveString();127 var chargeCheck = await "https://upay.10010.com/npfwap/NpfMob/mobWapBankCharge/wapBankChargeCheck.action"128 .WithHeaders(new { Referer = "https://upay.10010.com/jf_wxgz" })129 .WithCookies(cookies)130 .PostUrlEncodedAsync(new131 {132 phoneNo = phone,133 areaCode = "",134 provinceCode = "051",135 cityCode = "580",136 bussineTypeInput = "0",137 payAmount = 200,138 cardValue = "20000",139 cardValueCode = "10",140 userChooseMode = "0",141 reserved1 = false,142 numberType = "",143 channelType = 307,144 channelKey = "wxgz",145 bussineType = "06",146 netAccount = "",147 payMethod = "",148 internetThingsNumberFlag = "0",149 pointNumber = "",150 browserVersion = "",151 activityType = "",152 offerate = "1",153 offerateId = "",154 orgCode = "03",155 channelCode = "alipaywap",156 emergencyContact = "",157 ticketNo = "",158 reserved2 = "",159 ticketNew = "ticket",160 numberAttribution = "",161 urlSign = "",162 msgTimeStamp = "",163 serviceNo = "",164 natCode = "",165 saleChannel = "null",166 deviceId = "null",167 model = "null",168 vipCode = "",169 joinSign = "",170 presentActivityId = "",171 sinoUnionShortAddr = "",172 token = aliToken,173 sessionid = aliSessionId,174 sig = aliSig,175 state = dubbocheck.Secstate176 }).ReceiveJson<NeedDubboCheckInput>();177 var result = await "https://upay.10010.com/npfwap/NpfMob/mobWapBankCharge/wapBankChargeSubmit.action"178 .WithHeaders(new { Referer = "https://upay.10010.com/jf_wxgz" })179 .WithCookies(cookies)180 .PostUrlEncodedAsync(new181 {182 state = chargeCheck.Secstate,183 phoneNo = phone,184 provinceCode = "051",185 browserVersion = "",186 channelKey = "wxgz",187 ticketNew = "ticket"188 }).ReceiveString();189 }190 catch (Exception ex)191 {192 }193 //await page.EmulateAsync(Puppeteer.Devices[DeviceDescriptorName.IPhone8Plus]);194 //await page.GoToAsync("https://upay.10010.com/jf_wxgz");195 //await page.SetCookieAsync(new CookieParam { Name = "key", Value = "value", SameSite = SameSite.None, Secure = true });196 //string phone = "13113075869";197 //await page.ClickAsync("#number");198 //await page.TypeAsync("#number", phone);199 //Thread.Sleep(3000);200 //await page.ClickAsync("#cardlist > section > div.mobile-cardlist.cardlista > a:nth-child(1)");201 //await browser.CloseAsync();202 //await browser.DisposeAsync();203 //await page.EvaluateExpressionAsync($"document.getElementById('number').value={phone}");204 //var input = await page.("#number", "13113075869");205 //await input.EvaluateFunctionAsync("#number", "131125836985");206 //await page.ScreenshotAsync(outputFile);207 }208 }209}...
WebScraper.cs
Source:WebScraper.cs
...16 private readonly Page m_page;17 private decimal m_MouseX = 0;18 private decimal m_MouseY = 0;19 /// <summary>20 /// Defualt agent string this library uses. Simulates Chrome installed on windows 10.21 /// </summary>22 public static readonly string DefaultAgent =23 "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36";24 /// <summary>25 /// Constructor.26 /// </summary>27 /// <param name="headless">Set to false to show chromium window.</param>28 /// <param name="agent">Agent to use when accessing pages. Uses DefaultAgent if non is set.</param>29 public WebScraper(bool headless = true, string agent = "")30 {31 if (agent == "")32 agent = DefaultAgent;33 var ops = new BrowserFetcherOptions34 {35 Path = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\scraperion\\browser"36 };37 (new BrowserFetcher(ops).DownloadAsync(BrowserFetcher.DefaultRevision)).Wait();38 var browser = Puppeteer.LaunchAsync(new LaunchOptions39 {40 Headless = headless,41 IgnoreHTTPSErrors = true,42 });43 browser.Wait();44 m_browser = browser.Result;45 var page = m_browser.NewPageAsync();46 page.Wait();47 m_page = page.Result;48 m_page.Error += (s, e) => {49 Console.WriteLine("Error:" + e.ToString());50 };51 m_page.PageError += (s, e) =>52 {53 Console.WriteLine("Error:" + e.ToString());54 };55 m_page.Console += (s, e) => { Console.WriteLine(e.Message.Text); };56 m_page.SetUserAgentAsync(agent).Wait();57 }58 /// <summary>59 /// Set username and password to authenticate against web pages with.60 /// </summary>61 /// <param name="username">Username to authenticate with</param>62 /// <param name="password">Password to autrhenticate with.</param>63 public void SetAuth(string username, string password)64 {65 SetAuthAsync(username, password).Wait();66 }67 private async Task SetAuthAsync(string username, string password)68 {69 await m_page.AuthenticateAsync(new Credentials {Username = username, Password = password});70 }71 /// <summary>72 /// Sets the view port size of the page.73 /// </summary>74 /// <param name="width">Width of the page in pixels.</param>75 /// <param name="height">Height of page in pixels.</param>76 public void SetViewPort(int width, int height)77 {78 SetViewPortAsync(width, height).Wait();79 }80 private async Task SetViewPortAsync(int width, int height)81 {82 await m_page.SetViewportAsync(new ViewPortOptions83 {84 Width = width,85 Height = height86 });87 }88 /// <summary>89 /// Gets or sets the url the page is currently at.90 /// </summary>91 public string Url92 {93 get => m_page.Url;94 set95 {96 try97 {98 m_page.GoToAsync(value).Wait();99 }100 catch (Exception e)101 {102 Console.WriteLine(e);103 }104 }105 }106 /// <summary>107 /// Executes a javascript expression on page.108 /// This is simuilar to typing a command in the java console.109 /// </summary>110 /// <param name="script">Expression to run.</param>111 /// <returns>Json of executed result.</returns>112 public string Exec(string script)113 {114 var result = ExecAsync(script);115 result.Wait();116 return result.Result;117 }118 private async Task<string> ExecAsync(string script)119 {120 var data = await m_page.EvaluateExpressionAsync(script);121 return (string)data.ToString();122 }123 /// <summary>124 /// Takes a screenshot of the target page.125 /// </summary>126 /// <returns>Bitmap image containing screenshot.</returns>127 public Bitmap SnapshotBitmap()128 {129 var result = SnapshotBitmapAsync();130 result.Wait();131 return result.Result;132 }133 private async Task<Bitmap> SnapshotBitmapAsync()134 {135 var data = await m_page.ScreenshotStreamAsync();136 var image = new Bitmap(data);137 data.Dispose();138 return image;139 }140 /// <summary>141 /// Simulates key presses on page.142 /// </summary>143 /// <param name="text">Text to send to page.</param>144 public void SendKeys(string text)145 {146 SendKeysAsync(text).Wait();147 }148 private async Task SendKeysAsync(string text)149 {150 await m_page.Keyboard.TypeAsync(text);151 }152 /// <summary>153 /// Simulates moving the mouse on the page.154 ///155 /// Note: this does not move the system mouse.156 /// </summary>157 /// <param name="x">X coordinates to move mouse to.</param>158 /// <param name="y">Y coordinates to move mouse to.</param>159 public void MoveMouse(decimal x, decimal y)160 {161 MoveMouseAsync(x, y).Wait();162 }163 private async Task MoveMouseAsync(decimal x, decimal y)164 {165 await m_page.Mouse.MoveAsync(x, y);166 m_MouseX = x;167 m_MouseY = y;168 }169 /// <summary>170 /// Simulates a mouse click on page.171 /// </summary>172 /// <param name="button">Mouse button to simulate.</param>173 public void MouseClick(MouseButton button)174 {175 MouseClickAsync(button).Wait();176 }177 private async Task MouseClickAsync(MouseButton button)178 {179 await m_page.Mouse.ClickAsync(m_MouseX, m_MouseY, new ClickOptions{ Button = button == MouseButton.Left ? PuppeteerSharp.Input.MouseButton.Left : PuppeteerSharp.Input.MouseButton.Right });180 }181 /// <summary>182 /// Simulates a mouse up event on page.183 /// </summary>184 /// <param name="button">Mouse button to simulate.</param>185 public void MouseUp(MouseButton button)186 {187 MouseUpAsync(button).Wait();188 189 }190 private async Task MouseUpAsync(MouseButton button)191 {192 await m_page.Mouse.UpAsync(new ClickOptions { Button = button == MouseButton.Left ? PuppeteerSharp.Input.MouseButton.Left : PuppeteerSharp.Input.MouseButton.Right });193 }194 /// <summary>195 /// Simulates a mouse down event on page.196 /// </summary>197 /// <param name="button">Mouse button to simulate.</param>198 public void MouseDown(MouseButton button)199 {200 MouseDownAsync(button).Wait();201 }202 private async Task MouseDownAsync(MouseButton button)203 {204 await m_page.Mouse.DownAsync(new ClickOptions { Button = button == MouseButton.Left ? PuppeteerSharp.Input.MouseButton.Left : PuppeteerSharp.Input.MouseButton.Right });205 }206 /// <summary>207 /// Simulates a touch tap on a page.208 /// </summary>209 /// <param name="target">Javascript selector for element to tap on.</param>210 public void TapScreen(string target)211 {212 TapScreenAsync(target).Wait();213 }214 private async Task TapScreenAsync(string target)215 {216 await m_page.TapAsync(target);217 }218 /// <summary>219 /// Generates a pdf of the page.220 /// </summary>221 /// <returns>Stream containing the pdf data.</returns>222 public Stream CreatePdf()223 {224 var data = CreatePdfAsync();225 data.Wait();226 return data.Result;227 }228 private async Task<Stream> CreatePdfAsync()229 {230 return await m_page.PdfStreamAsync();231 }232 /// <summary>233 /// Waits for expression to be to be true.234 /// </summary>235 /// <param name="expression">Expression to wait on.</param>236 public void WaitOnScript(string expression)237 {238 WaitOnScriptAsync(expression).Wait();239 }240 private async Task WaitOnScriptAsync(string expression)241 {242 await m_page.WaitForExpressionAsync(expression);243 }244 /// <summary>245 /// Selects element on page to have focus.246 /// </summary>247 /// <param name="target">Javascript selector to make have focus.</param>248 public void Focus(string target)249 {250 FocusAsync(target).Wait();251 }252 private async Task FocusAsync(string target)253 {254 await m_page.FocusAsync(target);255 }256 /// <summary>257 /// Clicks on target element on page.258 /// </summary>259 /// <param name="target">Javascript selector of element to click on.</param>260 public void Click(string target)261 {262 ClickAsync(target).Wait();263 }264 private async Task ClickAsync(string target)265 {266 await m_page.ClickAsync(target);267 }268 /// <summary>269 /// Html content of page. Useful for scraping the html directly.270 /// </summary>271 public string Content272 {273 get274 {275 var data = m_page.GetContentAsync();276 data.Wait();277 return data.Result;278 }279 set280 {281 var data = m_page.SetContentAsync(value);282 data.Wait();283 }284 }285 /// <inheritdoc />...
BaseAuthUIFixture.cs
Source:BaseAuthUIFixture.cs
...15{16 public abstract class BaseAuthUIFixture : BaseUIFixture17 {18 private bool Authorized = false;19 protected abstract string AuthUrl { get; }20 protected BaseAuthUIFixture(int w, int h, Func<IHostBuilder> builderFunc) : base(w, h, builderFunc) {}21 [SetUp] 22 public void AuthSetUp()23 {24 var testObj = TestExecutionContext.CurrentContext.TestObject as BaseAuthUIFixture;25 var testType = testObj.GetType();26 var method = testType.GetMethods().SingleOrDefault(x => x.Name == TestContext.CurrentContext.Test.MethodName);27 if (method?.GetCustomAttributes(typeof(RequiresAuthAttribute), true).SingleOrDefault() is RequiresAuthAttribute raa)28 testObj.AzureADLogin().Wait();29 }30 [OneTimeTearDown]31 public void AuthTearDown()32 {33 Authorized = false;...
Program.cs
Source:Program.cs
...10 // My Products (https://browseasy.com/products/) page.1112 // Assuming that it's stored in the environment variables, 13 // e.g. wss://freemium.browseasy.com14 static readonly string BROWSEASY_ENDPOINT =15 Environment.GetEnvironmentVariable("BROWSEASY_ENDPOINT");1617 // Assuming that it's stored in the environment variables18 // e.g. ccc70169f82f4c7c8a33ecca21c1becf19 static readonly string BROWSEASY_API_KEY =20 Environment.GetEnvironmentVariable("BROWSEASY_API_KEY");2122 // Your unique connection string.23 static readonly string BROWSEASY_CONNECTION_STRING = $"{BROWSEASY_ENDPOINT}?code={BROWSEASY_API_KEY}";2425 // Your unique connection string with stealth mode enabled.26 static readonly string BROWSEASY_STEALTH_CONNECTION_STRING = $"{BROWSEASY_CONNECTION_STRING}&stealth";2728 // Debug endpoint29 static readonly string BROWSEASY_DEBUG_ENDPOINT = "https://debug.browseasy.com/inspector.html?remoteFrontend=true";3031 public static void OpenBrowser(string uri)32 {33 var psi = new System.Diagnostics.ProcessStartInfo();34 psi.UseShellExecute = true;35 psi.FileName = uri;36 System.Diagnostics.Process.Start(psi);37 }3839 public static async Task Main()40 {41 var options = new ConnectOptions()42 {43 BrowserWSEndpoint = BROWSEASY_STEALTH_CONNECTION_STRING,44 // Always reset default viewport.45 // When stealth mode enabled, Browseasy will launch your browser
...
PageObjects.cs
Source:PageObjects.cs
...14 public class GitHubHeaderMenu : ElementObject15 {16 [Selector("input.header-search-input")]17 public virtual Task<ElementHandle> SearchInput { get; }18 public async Task<GitHubSearchPage> Search(string text)19 {20 var input = await SearchInput;21 if (await input.IsHiddenAsync()) await Page.ClickAsync(".octicon-three-bars");22 await input.TypeAsync(text);23 await input.PressAsync(Key.Enter);24 return await Page.WaitForNavigationAsync<GitHubSearchPage>();25 }26 }27 public class GitHubSearchPage : PageObject28 {29 [Selector(".repo-list-item")]30 public virtual Task<GitHubRepoListItem[]> RepoListItems { get; }31 }32 public class GitHubRepoListItem : ElementObject33 {34 [Selector("a")]35 public virtual Task<ElementHandle> Link { get; }36 [Selector("p")]37 public virtual Task<ElementHandle> Text { get; }38 }39 public class GitHubRepoPage : PageObject40 {41 [Selector("article > h1")]42 public virtual Task<ElementHandle> Heading { get; }43 [Selector("img[alt='Build status']")]44 public virtual Task<ElementHandle> BuildStatusBadge { get; }45 public async Task<string> GetLatestReleaseVersion()46 {47 var latest = await Page.QuerySelectorWithContentAsync("a[href*='releases'] span", @"v\d+\.\d\.\d");48 return await latest.TextContentAsync();49 }50 }51 public class AppVeyorBuildPage : PageObject52 {53 public async Task<bool> Success()54 {55 var success = await Page.QuerySelectorAsync(".project-build.project-build-status.success");56 return success.Exists();57 }58 }59}...
ConcurrentBrowserActivities.cs
Source:ConcurrentBrowserActivities.cs
...12{13 public static class ConcurrentBrowserActivities14 {15 [FunctionName("A_NavigateNewPage")]16 public static async Task<string> ProcessVideo(17 [ActivityTrigger] DurableActivityContext ctx,18 TraceWriter log19 )20 {21 var url = ctx.GetInput<string>();22 var asm = Assembly.Load("Microsoft.Extensions.Options, Culture=neutral, PublicKeyToken=adb9793829ddae60");23 PuppeteerSharp.Browser browser = null;24 try25 {26 browser = await Puppeteer.ConnectAsync(new ConnectOptions { BrowserWSEndpoint = Constants.BrowserWSEndpoint });27 var page = await browser.NewPageAsync();28 await page.GoToAsync(url, new NavigationOptions { Timeout = 4000 });29 }30 catch (Exception ex)31 {32 return ex.Message;33 }34 finally35 {36 if (browser != null)37 {38 browser.Disconnect();39 }40 }41 return $"Processed {url} shit all.";42 }43 [FunctionName("A_Worker")]44 public static async Task<string> Worker(45 [ActivityTrigger] DurableActivityContext ctx,46 TraceWriter log47 )48 {49 return "";50 }51 }52 public static class Constants53 {54 public static string BrowserWSEndpoint = "ws://localhost:9222/devtools/browser/d326cbdc-0779-41de-bfb4-18d89e3bd310";55 }56}...
KeyboardPressFunction.cs
Source:KeyboardPressFunction.cs
...5{6 public class KeyboardPressFunction : FunctionBase, IInteractionFunction7 {8 #region Properties9 public override string Name => "keypress";10 protected override FunctionParameter[] DefaultParameters11 {12 get13 {14 return new FunctionParameter[]15 {16 new FunctionParameter<string>17 {18 Name = "key"19 },20 new FunctionParameter<int?>21 {22 Name = "delay"23 }24 };25 }26 }27 #endregion28 #region Methods29 public async Task ExecuteAsync(Page page)30 {31 var key = this.GetParameterValue<string>("key");32 var delay = this.GetParameterValue<int?>("delay");33 var pressOptions = delay != null ? new PressOptions { Delay = delay.Value } : null;34 await page.Keyboard.PressAsync(key, pressOptions);35 }36 #endregion37 }38}
string
Using AI Code Generation
1await page.Keyboard.PressAsync("ShiftLeft");2await page.Keyboard.PressAsync("ShiftRight");3await page.Keyboard.PressAsync("ControlLeft");4await page.Keyboard.PressAsync("ControlRight");5await page.Keyboard.PressAsync("AltLeft");6await page.Keyboard.PressAsync("AltRight");7await page.Keyboard.PressAsync("Shift");8await page.Keyboard.PressAsync("Control");9await page.Keyboard.PressAsync("Alt");10await page.Keyboard.PressAsync("ShiftLeft", "ControlLeft", "AltLeft");11await page.Keyboard.DownAsync("ShiftLeft");12await page.Keyboard.DownAsync("ControlLeft");13await page.Keyboard.DownAsync("AltLeft");14await page.Keyboard.UpAsync("ShiftLeft");15await page.Keyboard.UpAsync("ControlLeft");16await page.Keyboard.UpAsync("AltLeft");17await page.Keyboard.DownAsync("Shift");18await page.Keyboard.DownAsync("Control");19await page.Keyboard.DownAsync("Alt");20await page.Keyboard.UpAsync("Shift");21await page.Keyboard.UpAsync("Control");22await page.Keyboard.UpAsync("Alt");23await page.Keyboard.DownAsync("ShiftLeft", "ControlLeft", "AltLeft");24await page.Keyboard.UpAsync("ShiftLeft", "ControlLeft", "AltLeft");25await page.Keyboard.DownAsync("Shift", "Control", "Alt");26await page.Keyboard.UpAsync("Shift", "Control", "Alt");27await page.Keyboard.DownAsync("ShiftLeft", "ControlLeft");28await page.Keyboard.DownAsync("AltLeft");29await page.Keyboard.UpAsync("ShiftLeft", "ControlLeft");30await page.Keyboard.UpAsync("AltLeft");31await page.Keyboard.DownAsync("Shift", "Control");32await page.Keyboard.DownAsync("Alt");33await page.Keyboard.UpAsync("Shift", "Control");34await page.Keyboard.UpAsync("Alt");35await page.Keyboard.DownAsync("ShiftLeft");36await page.Keyboard.DownAsync("ControlLeft");
string
Using AI Code Generation
1await page.Keyboard.TypeAsync("Hello World");2await page.Keyboard.PressAsync("Enter");3await page.Keyboard.TypeAsync("Hello World");4await page.Keyboard.PressAsync("Enter");5await page.Keyboard.TypeAsync("Hello World");6await page.Keyboard.PressAsync("Enter");7await page.Keyboard.TypeAsync("Hello World");8await page.Keyboard.PressAsync("Enter");9await page.Keyboard.TypeAsync("Hello World");10await page.Keyboard.PressAsync("Enter");11await page.Keyboard.TypeAsync("Hello World");12await page.Keyboard.PressAsync("Enter");13await page.Keyboard.TypeAsync("Hello World");14await page.Keyboard.PressAsync("Enter");15await page.Keyboard.TypeAsync("Hello World");16await page.Keyboard.PressAsync("Enter");17await page.Keyboard.TypeAsync("Hello World");18await page.Keyboard.PressAsync("Enter");19await page.Keyboard.TypeAsync("Hello World");
string
Using AI Code Generation
1await page.Keyboard.TypeAsync("Hello World");2await page.Keyboard.TypeAsync(PuppeteerSharp.Input.Key.Enter);3await page.Keyboard.TypeAsync("Hello World");4await page.Keyboard.TypeAsync(PuppeteerSharp.Input.Key.Enter);5await page.Keyboard.TypeAsync("Hello World");6await page.Keyboard.TypeAsync(PuppeteerSharp.Input.Key.Enter);7await page.Keyboard.TypeAsync("Hello World");8await page.Keyboard.TypeAsync(PuppeteerSharp.Input.Key.Enter);9await page.Keyboard.TypeAsync("Hello World");10await page.Keyboard.TypeAsync(PuppeteerSharp.Input.Key.Enter);11await page.Keyboard.TypeAsync("Hello World");12await page.Keyboard.TypeAsync(PuppeteerSharp.Input.Key.Enter);13await page.Keyboard.TypeAsync("Hello World");14await page.Keyboard.TypeAsync(PuppeteerSharp.Input.Key.Enter);15await page.Keyboard.TypeAsync("Hello World");16await page.Keyboard.TypeAsync(PuppeteerSharp.Input.Key.Enter);17await page.Keyboard.TypeAsync("Hello World");18await page.Keyboard.TypeAsync(PuppeteerSharp.Input.Key.Enter);19await page.Keyboard.TypeAsync("Hello World");
string
Using AI Code Generation
1await page.Keyboard.TypeAsync("Hello World");2await page.Keyboard.PressAsync(PuppeteerSharp.Input.Key.Enter);3await page.Keyboard.PressAsync(PuppeteerSharp.Input.Key.Escape);4await page.Keyboard.PressAsync(PuppeteerSharp.Input.Key.Backspace);5await page.Keyboard.PressAsync("Hello World");6await page.Keyboard.TypeAsync(PuppeteerSharp.Input.Key.Enter);7await page.Keyboard.TypeAsync(PuppeteerSharp.Input.Key.Escape);8await page.Keyboard.TypeAsync(PuppeteerSharp.Input.Key.Backspace);9await page.Keyboard.PressAsync("Hello World");10await page.Keyboard.TypeAsync(PuppeteerSharp.Input.Key.Enter);11await page.Keyboard.TypeAsync(PuppeteerSharp.Input.Key.Escape);12await page.Keyboard.TypeAsync(PuppeteerSharp.Input.Key.Backspace);13await page.Keyboard.PressAsync("Hello World");14await page.Keyboard.TypeAsync(PuppeteerSharp.Input.Key.Enter);15await page.Keyboard.TypeAsync(PuppeteerSharp.Input.Key.Escape);16await page.Keyboard.TypeAsync(PuppeteerSharp.Input.Key.Backspace);17await page.Keyboard.PressAsync("Hello World");18await page.Keyboard.TypeAsync(PuppeteerSharp.Input.Key.Enter);19await page.Keyboard.TypeAsync(PuppeteerSharp.Input.Key.Escape);20await page.Keyboard.TypeAsync(PuppeteerSharp.Input.Key.Backspace);21await page.Keyboard.PressAsync("Hello World");22await page.Keyboard.TypeAsync(PuppeteerSharp.Input.Key.Enter);23await page.Keyboard.TypeAsync(PuppeteerSharp.Input.Key.Escape);24await page.Keyboard.TypeAsync(PuppeteerSharp.Input.Key.Backspace);
string
Using AI Code Generation
1var page = await browser.NewPageAsync();2await page.Keyboard.TypeAsync("PuppeteerSharp");3await page.Keyboard.PressAsync("Enter");4var page = await browser.NewPageAsync();5await page.Keyboard.TypeAsync("PuppeteerSharp");6await page.Keyboard.PressAsync(PuppeteerSharp.Input.Key.Enter);7var page = await browser.NewPageAsync();8await page.Keyboard.TypeAsync("PuppeteerSharp");9await page.Keyboard.PressAsync("Enter");10var page = await browser.NewPageAsync();11await page.Keyboard.TypeAsync("PuppeteerSharp");12await page.Keyboard.PressAsync(PuppeteerSharp.Input.Key.Enter);13var page = await browser.NewPageAsync();14await page.Keyboard.TypeAsync("PuppeteerSharp");15await page.Keyboard.PressAsync("Enter");16var page = await browser.NewPageAsync();17await page.Keyboard.TypeAsync("PuppeteerSharp");18await page.Keyboard.PressAsync(PuppeteerSharp.Input.Key.Enter);19var page = await browser.NewPageAsync();20await page.Keyboard.TypeAsync("PuppeteerSharp");21await page.Keyboard.PressAsync("Enter");22var page = await browser.NewPageAsync();23await page.Keyboard.TypeAsync("PuppeteerSharp");24await page.Keyboard.PressAsync(PuppeteerSharp.Input.Key.Enter);25var page = await browser.NewPageAsync();
string
Using AI Code Generation
1await page.Keyboard.TypeAsync("Hello World!");2await page.Keyboard.TypeAsync("Hello World!", new Dictionary<string, object> { { "delay", 100 } });3await page.Keyboard.PressAsync("Enter");4await page.Keyboard.PressAsync("Enter", new Dictionary<string, object> { { "delay", 100 } });5await page.Keyboard.TypeAsync("Hello World!");6await page.Keyboard.TypeAsync("Hello World!", new Dictionary<string, object> { { "delay", 100 } });7await page.Keyboard.PressAsync("Enter");8await page.Keyboard.PressAsync("Enter", new Dictionary<string, object> { { "delay", 100 } });9await page.Keyboard.TypeAsync("Hello World!");10await page.Keyboard.TypeAsync("Hello World!", new Dictionary<string, object> { { "delay", 100 } });11await page.Keyboard.PressAsync("Enter");12await page.Keyboard.PressAsync("Enter", new Dictionary<string, object> { { "delay", 100 } });13await page.Keyboard.TypeAsync("Hello World!");14await page.Keyboard.TypeAsync("Hello World!", new Dictionary<string, object> { { "delay", 100 } });15await page.Keyboard.PressAsync("Enter");16await page.Keyboard.PressAsync("Enter", new Dictionary<string, object> { { "delay", 100 } });
string
Using AI Code Generation
1var key = new PuppeteerSharp.Input.Key();2await page.TypeAsync("#myInput", key.Enter);3var key = new PuppeteerSharp.Input.Key();4await page.TypeAsync("#myInput", key.Enter);5var key = new PuppeteerSharp.Input.Key();6await page.TypeAsync("#myInput", key.Enter);7var key = new PuppeteerSharp.Input.Key();8await page.TypeAsync("#myInput", key.Enter);9var key = new PuppeteerSharp.Input.Key();10await page.TypeAsync("#myInput", key.Enter);11var key = new PuppeteerSharp.Input.Key();12await page.TypeAsync("#myInput", key.Enter);13var key = new PuppeteerSharp.Input.Key();14await page.TypeAsync("#myInput", key.Enter);15var key = new PuppeteerSharp.Input.Key();16await page.TypeAsync("#myInput", key.Enter);17var key = new PuppeteerSharp.Input.Key();18await page.TypeAsync("#myInput", key.Enter);
string
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static void Main(string[] args)7 {8 MainAsync().Wait();9 }10 static async Task MainAsync()11 {12 var browser = await Puppeteer.LaunchAsync(new LaunchOptions13 {14 });15 var page = await browser.NewPageAsync();16 await page.TypeAsync("input[name='q']", "Puppeteer Sharp");17 await page.ClickAsync("input[name='btnK']");18 await page.WaitForNavigationAsync();19 await page.ScreenshotAsync("result.png");20 await browser.CloseAsync();21 }22 }23}24using System;25using System.Threading.Tasks;26using PuppeteerSharp;27{28 {29 static void Main(string[] args)30 {31 MainAsync().Wait();32 }33 static async Task MainAsync()34 {35 var browser = await Puppeteer.LaunchAsync(new LaunchOptions36 {37 });38 var page = await browser.NewPageAsync();39 await page.Keyboard.TypeAsync("Puppeteer Sharp");40 await page.ClickAsync("input[name='btnK']");41 await page.WaitForNavigationAsync();42 await page.ScreenshotAsync("result.png");43 await browser.CloseAsync();44 }45 }46}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!