zoukankan      html  css  js  c++  java
  • PuppeteerSharp体验之旅

      public static async Task<string> LogInAsync()
            {
                try
                {
                    string ResultCookies = "";
                    //获取用户名
                    string UserName = Environment.UserName;
    
                    var currentDirectory = Path.Combine(@"C:Users", UserName, @"AppDataLocalGoogleChromeApplication", "Chrome.exe");//string currentDirectory = Path.GetDirectoryName(@"C:UsersTTAppDataLocalGoogleChromeApplication"); //指定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.
     Press any key to continue");
                                Console.ReadLine();
                                return "Custom Chromium location is empty. Unable to start Chromium. Exiting.
     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

  • 相关阅读:
    PHP返回随机颜色
    SQL Server 系统表介绍:sys.dm_exec_requests
    ORA27300 ORA27301 ORA27302 ORA27157
    Linux的subversion安装配置
    批处理计算n天前\后的日期
    Linux下vsftp配置
    RedHat Linux 5企业版开启VNCSERVER远程桌面功能
    WAS 6.1命令行(静默)安装
    五板斧封杀Windows操作系统默认共享(图)
    Select Top在不同数据库中的使用用法:
  • 原文地址:https://www.cnblogs.com/TTonly/p/10920294.html
Copyright © 2011-2022 走看看