コード例 #1
0
        private static string ResolveExecutablePath()
        {
            var executablePath = Environment.GetEnvironmentVariable("PUPPETEER_EXECUTABLE_PATH");

            if (!string.IsNullOrEmpty(executablePath))
            {
                if (!File.Exists(executablePath))
                {
                    throw new FileNotFoundException("Tried to use PUPPETEER_EXECUTABLE_PATH env variable to launch browser but did not find any executable", executablePath);
                }
                return(executablePath);
            }

            var          browserFetcher = new BrowserFetcher();
            var          revision       = Environment.GetEnvironmentVariable("PUPPETEER_CHROMIUM_REVISION");
            RevisionInfo revisionInfo;

            if (!string.IsNullOrEmpty(revision) && int.TryParse(revision, out var revisionNumber))
            {
                revisionInfo = browserFetcher.RevisionInfo(revisionNumber);
                if (!revisionInfo.Local)
                {
                    throw new FileNotFoundException("Tried to use PUPPETEER_CHROMIUM_REVISION env variable to launch browser but did not find executable", revisionInfo.ExecutablePath);
                }
                return(revisionInfo.ExecutablePath);
            }
            revisionInfo = browserFetcher.RevisionInfo(BrowserFetcher.DefaultRevision);
            if (!revisionInfo.Local)
            {
                throw new FileNotFoundException("Chromium revision is not downloaded. Run BrowserFetcher.DownloadAsync or download Chromium manually", revisionInfo.ExecutablePath);
            }
            return(revisionInfo.ExecutablePath);
        }
コード例 #2
0
        internal static string[] GetDefaultArgs(LaunchOptions options)
        {
            var chromeArguments = new List <string>(DefaultArgs);

            if (!string.IsNullOrEmpty(options.UserDataDir))
            {
                chromeArguments.Add($"{UserDataDirArgument}={options.UserDataDir.Quote()}");
            }
            if (options.Devtools)
            {
                chromeArguments.Add("--auto-open-devtools-for-tabs");
            }
            if (options.Headless)
            {
                chromeArguments.AddRange(new[] {
                    "--headless",
                    "--hide-scrollbars",
                    "--mute-audio"
                });
                if (BrowserFetcher.GetCurrentPlatform() == Platform.Win32)
                {
                    chromeArguments.Add("--disable-gpu");
                }
            }

            if (options.Args.All(arg => arg.StartsWith("-", StringComparison.Ordinal)))
            {
                chromeArguments.Add("about:blank");
            }

            chromeArguments.AddRange(options.Args);
            return(chromeArguments.ToArray());
        }
コード例 #3
0
        private async Task <string> ResolveExecutablePathAsync()
        {
            var executablePath = Environment.GetEnvironmentVariable("PUPPETEER_EXECUTABLE_PATH");

            if (!string.IsNullOrEmpty(executablePath))
            {
                if (!File.Exists(executablePath))
                {
                    throw new FileNotFoundException("Tried to use PUPPETEER_EXECUTABLE_PATH env variable to launch browser but did not find any executable", executablePath);
                }
                return(executablePath);
            }

            var revision = Environment.GetEnvironmentVariable("PUPPETEER_CHROMIUM_REVISION");

            using var browserFetcher = new BrowserFetcher(_product);
            RevisionInfo revisionInfo;

            if (!string.IsNullOrEmpty(revision))
            {
                revisionInfo = browserFetcher.RevisionInfo(revision);
                if (!revisionInfo.Local)
                {
                    throw new FileNotFoundException("Tried to use PUPPETEER_CHROMIUM_REVISION env variable to launch browser but did not find executable", revisionInfo.ExecutablePath);
                }
                return(revisionInfo.ExecutablePath);
            }
            revisionInfo = await browserFetcher.GetRevisionInfoAsync().ConfigureAwait(false);

            if (!revisionInfo.Local)
            {
                throw new FileNotFoundException("Process revision is not downloaded. Run BrowserFetcher.DownloadAsync or download the process manually", revisionInfo.ExecutablePath);
            }
            return(revisionInfo.ExecutablePath);
        }
コード例 #4
0
        /// <summary>
        /// The method launches a browser instance with given arguments. The browser will be closed when the Browser is disposed.
        /// </summary>
        /// <param name="options">Options for launching Chrome</param>
        /// <returns>A connected browser.</returns>
        /// <remarks>
        /// See <a href="https://www.howtogeek.com/202825/what%E2%80%99s-the-difference-between-chromium-and-chrome/">this article</a>
        /// for a description of the differences between Chromium and Chrome.
        /// <a href="https://chromium.googlesource.com/chromium/src/+/lkcr/docs/chromium_browser_vs_google_chrome.md">This article</a> describes some differences for Linux users.
        /// </remarks>
        public async Task <Browser> LaunchAsync(LaunchOptions options)
        {
            if (_chromiumLaunched)
            {
                throw new InvalidOperationException("Unable to create or connect to another chromium process");
            }
            _chromiumLaunched = true;
            var chromeArguments  = InitChromeArgument(options);
            var chromeExecutable = options.ExecutablePath;

            if (string.IsNullOrEmpty(chromeExecutable))
            {
                var browserFetcher = new BrowserFetcher();
                chromeExecutable = browserFetcher.RevisionInfo(BrowserFetcher.DefaultRevision).ExecutablePath;
            }
            if (!File.Exists(chromeExecutable))
            {
                throw new FileNotFoundException("Failed to launch chrome! path to executable does not exist", chromeExecutable);
            }

            _chromeProcess = CreateChromeProcess(options, chromeArguments, chromeExecutable);
            try
            {
                var connectionDelay   = options.SlowMo;
                var browserWSEndpoint = await WaitForEndpoint(_chromeProcess, options.Timeout).ConfigureAwait(false);

                try
                {
                    var keepAliveInterval = 0;
                    _connection = await Connection
                                  .Create(browserWSEndpoint, connectionDelay, keepAliveInterval, _loggerFactory)
                                  .ConfigureAwait(false);

                    var browser = await Browser.CreateAsync(
                        _connection,
                        Array.Empty <string>(),
                        options.IgnoreHTTPSErrors,
                        !options.AppMode,
                        _chromeProcess,
                        GracefullyCloseChrome
                        )
                                  .ConfigureAwait(false);

                    await EnsureInitialPageAsync(browser).ConfigureAwait(false);

                    return(browser);
                }
                catch (Exception ex)
                {
                    throw new ChromeProcessException("Failed to create connection", ex);
                }
            }
            catch
            {
                KillChrome();
                await _chromeCloseTcs.Task.ConfigureAwait(false);

                throw;
            }
        }
コード例 #5
0
ファイル: Program.cs プロジェクト: Viir/bots-test-github
    static async System.Threading.Tasks.Task StartWebBrowser()
    {
        var browserRevision = PuppeteerSharp.BrowserFetcher.DefaultChromiumRevision;

        var browserFetcher = new PuppeteerSharp.BrowserFetcher(new PuppeteerSharp.BrowserFetcherOptions
        {
            Path = BrowserDownloadDirPath()
        });

        await browserFetcher.DownloadAsync(browserRevision);

        browser = await PuppeteerSharp.Puppeteer.LaunchAsync(new PuppeteerSharp.LaunchOptions
        {
            Headless        = false,
            UserDataDir     = UserDataDirPath("default"),
            DefaultViewport = null,
            ExecutablePath  = browserFetcher.RevisionInfo(browserRevision).ExecutablePath,
        });

        browserPage = (await browser.PagesAsync()).FirstOrDefault() ?? await browser.NewPageAsync();

        await browserPage.ExposeFunctionAsync("____callback____", (string returnValue) =>
        {
            callbackFromBrowserDelegate?.Invoke(returnValue);
            return(0);
        });
    }
コード例 #6
0
ファイル: Launcher.cs プロジェクト: VAllens/puppeteer-sharp
        /// <summary>
        /// The method launches a browser instance with given arguments. The browser will be closed when the Browser is disposed.
        /// </summary>
        /// <param name="options">Options for launching Chrome</param>
        /// <returns>A connected browser.</returns>
        /// <remarks>
        /// See <a href="https://www.howtogeek.com/202825/what%E2%80%99s-the-difference-between-chromium-and-chrome/">this article</a>
        /// for a description of the differences between Chromium and Chrome.
        /// <a href="https://chromium.googlesource.com/chromium/src/+/lkcr/docs/chromium_browser_vs_google_chrome.md">This article</a> describes some differences for Linux users.
        /// </remarks>
        public async Task <Browser> LaunchAsync(LaunchOptions options)
        {
            if (_chromiumLaunched)
            {
                throw new InvalidOperationException("Unable to create or connect to another chromium process");
            }
            _chromiumLaunched = true;
            var chromeArguments  = InitChromeArgument(options);
            var chromeExecutable = options.ExecutablePath;

            if (string.IsNullOrEmpty(chromeExecutable))
            {
                var browserFetcher = new BrowserFetcher();
                chromeExecutable = browserFetcher.RevisionInfo(BrowserFetcher.DefaultRevision).ExecutablePath;
            }
            if (!File.Exists(chromeExecutable))
            {
                throw new FileNotFoundException("Failed to launch chrome! path to executable does not exist", chromeExecutable);
            }

            CreateChromeProcess(options, chromeArguments, chromeExecutable);

            try
            {
                var connectionDelay   = options.SlowMo;
                var browserWSEndpoint = await WaitForEndpoint(_chromeProcess, options.Timeout, options.DumpIO);

                var keepAliveInterval = options.KeepAliveInterval;

                _connection = await Connection.Create(browserWSEndpoint, connectionDelay, keepAliveInterval, _loggerFactory);

                _processLoaded = true;

                if (options.LogProcess)
                {
                    _logger.LogInformation("Process Count: {ProcessCount}", Interlocked.Increment(ref _processCount));
                }

                return(await Browser.CreateAsync(_connection, options, _chromeProcess, KillChrome));
            }
            catch (Exception ex)
            {
                ForceKillChrome();
                throw new ChromeProcessException("Failed to create connection", ex);
            }
        }
コード例 #7
0
        private static string GetOrFetchChromeExecutable(LaunchOptions options)
        {
            var chromeExecutable = options.ExecutablePath;

            if (string.IsNullOrEmpty(chromeExecutable))
            {
                var browserFetcher = new BrowserFetcher();
                chromeExecutable = browserFetcher.RevisionInfo(BrowserFetcher.DefaultRevision).ExecutablePath;
            }

            if (!File.Exists(chromeExecutable))
            {
                throw new FileNotFoundException("Failed to launch chrome! path to executable does not exist", chromeExecutable);
            }

            return(chromeExecutable);
        }
コード例 #8
0
        public static async Task Main(string[] args)
        {
            var currentDirectory = Directory.GetCurrentDirectory();
            var downloadPath     = Path.Combine(currentDirectory, "CustomChromium");

            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 {
                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;
            }

            Console.WriteLine($"Attemping to start Chromium using executable path: {executablePath}");

            var options = new LaunchOptions {
                Headless = true, ExecutablePath = executablePath
            };

            using (var browser = await Puppeteer.LaunchAsync(options))
                using (var page = await browser.NewPageAsync())
                {
                    await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
                    await page.SetViewportAsync(new ViewPortOptions { Width = 1920, Height = 1080 });

                    var waitUntil = new NavigationOptions {
                        Timeout = 0, WaitUntil = new[] { WaitUntilNavigation.Networkidle0 }
                    };
                    string url = "https://github.com/puppeteer/puppeteer/issues/1345";
                    await page.GoToAsync(url, waitUntil);

                    #region Screenshot Dashboard:
                    var optionsScreenShot = new ScreenshotOptions {
                        FullPage = true
                    };
                    //Đường dẫn lưu file
                    var savePath = Path.Combine(currentDirectory, "Capture");
                    if (!Directory.Exists(savePath))
                    {
                        Console.WriteLine("SavePath directory not found. Creating directory");
                        Directory.CreateDirectory(savePath);
                    }
                    string date       = DateTime.Now.ToString("yyyyMMddHHmmss");
                    var    outputfile = savePath + "/capture_" + date + ".png";
                    await page.ScreenshotAsync(outputfile, optionsScreenShot);

                    Console.WriteLine("Capture completed! Path: " + outputfile, ConsoleColor.Green);
                    #endregion

                    await page.CloseAsync();
                }
            return;
        }