PuppeteerSharp体验之旅

  public static async Task<string> LogInAsync()
        {
            try
            {
                string ResultCookies = "";
                //获取用户名
                string UserName = Environment.UserName;

                var currentDirectory = Path.Combine(@"C:\Users\", UserName, @"AppData\Local\Google\Chrome\Application\", "Chrome.exe");//string currentDirectory = Path.GetDirectoryName(@"C:\Users\TT\AppData\Local\Google\Chrome\Application"); //指定Chrome.exe在这目录才行

                if (!File.Exists(currentDirectory))
                {
                    currentDirectory = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory);
                    var downloadPath = Path.Combine(currentDirectory,  "LocalChromium");
                    Console.WriteLine($"Attemping to set up puppeteer to use Chromium found under directory {downloadPath} ");
                    if (!Directory.Exists(downloadPath))
                    {
                        Console.WriteLine("Custom directory not found. Creating directory");
                        Directory.CreateDirectory(downloadPath);

                        Console.WriteLine("Downloading Chromium");

                        var browserFetcherOptions = new BrowserFetcherOptions { Host = "https://npm.taobao.org/mirrors", Path = downloadPath };//设置淘宝镜像
                        var browserFetcher = new BrowserFetcher(browserFetcherOptions);
                        await browserFetcher.DownloadAsync(BrowserFetcher.DefaultRevision);

                        var executablePath = browserFetcher.GetExecutablePath(BrowserFetcher.DefaultRevision);

                        if (string.IsNullOrEmpty(executablePath))
                        {
                            Console.WriteLine("Custom Chromium location is empty. Unable to start Chromium. Exiting.\n Press any key to continue");
                            Console.ReadLine();
                            return "Custom Chromium location is empty. Unable to start Chromium. Exiting.\n Press any key to continue";
                        }
                        Console.WriteLine($"Attemping to start Chromium using executable path: {executablePath}");
                        //Set Path
                        currentDirectory = Path.Combine(executablePath, "Chromium.exe");
                    }
                    else
                    {
                        //Set Path  这里没做下载失败的判断
                        currentDirectory = Path.Combine(downloadPath, "Chromium.exe");
                    }

                }

                var options = new LaunchOptions
                {
                    Headless = false,//无头
                    ExecutablePath = currentDirectory,//本地路径
                    Args = new string[]
                    {
                        "--disable-infobars",//隐藏 自动化标题
                    },//添加Argument 和webdriver一样吧
                    DefaultViewport = new ViewPortOptions
                    {
                        Width = 500,
                        Height = 500,
                        IsMobile = true,
                        //DeviceScaleFactor = 2
                    },
                    //SlowMo=250, // slow down by 250ms
                };

                using (var browser = await Puppeteer.LaunchAsync(options))
                using (var page = await browser.NewPageAsync())
                {
                    // disable images to download
                    //await page.SetRequestInterceptionAsync(true);
                    //page.Request += (sender, e) =>
                    //{
                    //    if (e.Request.ResourceType == ResourceType.Image)
                    //        e.Request.AbortAsync();
                    //    else
                    //        e.Request.ContinueAsync();
                    //};
                    //设置手机模式
                    DeviceDescriptor deviceOptions = Puppeteer.Devices.GetValueOrDefault(DeviceDescriptorName.IPhone7);
                    await page.EmulateAsync(deviceOptions);
                    //await page.SetUserAgentAsync("Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1");
        
                    await page.GoToAsync("https://www.baidu.com/");

                    // 登录
                    Console.WriteLine("Start Login!");
                    await page.GetContentAsync();
                    //输入
                    //ElementHandle input = await page.WaitForSelectorAsync("#search_form_input_homepage");
                    //await input.TypeAsync("Lorem ipsum dolor sit amet.");
                    await page.TypeAsync("input[name=id]", "yourname");
                    await page.TypeAsync("input[name=pwd]", "yourpassword");
                    await Task.WhenAll(page.ClickAsync("#login"), page.WaitForNavigationAsync());
                    Console.WriteLine("Finish Login!");
                   
                    //获取Cookies
                    //CookieParam[] cookies = await page.GetCookiesAsync();
      
                    Console.WriteLine(ResultCookies);
                    Console.WriteLine("Press any key to continue...");
                    Console.ReadLine();
                }
                return ResultCookies;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

官方代码

https://github.com/kblok/puppeteer-sharp

posted @ 2019-05-24 21:30  TTonlyV5  阅读(2844)  评论(4编辑  收藏  举报