Php работа с браузером

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Instrument headless chrome/chromium instances from PHP

License

chrome-php/chrome

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

This library lets you start playing with chrome/chromium in headless mode from PHP.

Can be used synchronously and asynchronously!

  • Open chrome or chromium browser from php
  • Create pages and navigate to pages
  • Take screenshots
  • Evaluate javascript on the page
  • Make PDF
  • Emulate mouse
  • Emulate keyboard
  • Always IDE friendly

Requires PHP 7.4-8.2 and a chrome/chromium 65+ executable.

Note that the library is only tested on Linux but is compatible with macOS and Windows.

The library can be installed with Composer and is available on packagist under chrome-php/chrome:

$ composer require chrome-php/chrome

It uses a simple and understandable API to start chrome, to open pages, take screenshots, crawl websites. and almost everything that you can do with chrome as a human.

use HeadlessChromium\BrowserFactory; $browserFactory = new BrowserFactory(); // starts headless chrome $browser = $browserFactory->createBrowser(); try < // creates a new page and navigate to an URL $page = $browser->createPage(); $page->navigate('http://example.com')->waitForNavigation(); // get page title $pageTitle = $page->evaluate('document.title')->getReturnValue(); // screenshot - Say "Cheese"! 😄 $page->screenshot()->saveToFile('/foo/bar.png'); // pdf $page->pdf(['printBackground' => false])->saveToFile('/foo/bar.pdf'); > finally < // bye $browser->close(); >

Using different chrome executable

When starting, the factory will look for the environment variable «CHROME_PATH» to use as the chrome executable. If the variable is not found, it will try to guess the correct executable path according to your OS or use «chrome» as the default.

You are also able to explicitly set up any executable of your choice when creating a new object. For instance «chromium-browser» :

use HeadlessChromium\BrowserFactory; // replace default 'chrome' with 'chromium-browser' $browserFactory = new BrowserFactory('chromium-browser');

The following example disables headless mode to ease debugging

use HeadlessChromium\BrowserFactory; $browserFactory = new BrowserFactory(); $browser = $browserFactory->createBrowser([ 'headless' => false, // disable headless mode ]);
[ 'connectionDelay' => 0.8, // add 0.8 second of delay between each instruction sent to chrome, 'debugLogger' => 'php://stdout', // will enable verbose mode ]

About debugLogger : this can be any of a resource string, a resource, or an object implementing LoggerInterface from Psr\Log (such as monolog or apix/log).

Options set directly in the createBrowser method will be used only for a single browser creation. The default options will be ignored.

use HeadlessChromium\BrowserFactory; $browserFactory = new BrowserFactory(); $browser = $browserFactory->createBrowser([ 'windowSize' => [1920, 1000], 'enableImages' => false, ]); // this browser will be created without any options $browser2 = $browserFactory->createBrowser();

Options set using the setOptions and addOptions methods will persist.

$browserFactory->setOptions([ 'windowSize' => [1920, 1000], ]); // both browser will have the same 'windowSize' option $browser1 = $browserFactory->createBrowser(); $browser2 = $browserFactory->createBrowser(); $browserFactory->addOptions(['enableImages' => false]); // this browser will have both the 'windowSize' and 'enableImages' options $browser3 = $browserFactory->createBrowser(); $browserFactory->addOptions(['enableImages' => true]); // this browser will have the previous 'windowSize', but 'enableImages' will be true $browser4 = $browserFactory->createBrowser();

Here are the options available for the browser factory:

Option name Default Description
connectionDelay 0 Delay to apply between each operation for debugging purposes
customFlags none An array of flags to pass to the command line. Eg: [‘—option1’, ‘—option2=someValue’]
debugLogger null A string (e.g «php://stdout»), or resource, or PSR-3 logger instance to print debug messages
disableNotifications false Disable browser notifications
enableImages true Toggles loading of images
envVariables none An array of environment variables to pass to the process (example DISPLAY variable)
headers none An array of custom HTTP headers
headless true Enable or disable headless mode
ignoreCertificateErrors false Set chrome to ignore ssl errors
keepAlive false Set to true to keep alive the chrome instance when the script terminates
noSandbox false Enable no sandbox mode, useful to run in a docker container
noProxyServer false Don’t use a proxy server, always make direct connections. Overrides other proxy settings.
proxyBypassList none Specifies a list of hosts for whom we bypass proxy settings and use direct connections
proxyServer none Proxy server to use. usage: 127.0.0.1:8080 (authorisation with credentials does not work)
sendSyncDefaultTimeout 5000 Default timeout (ms) for sending sync messages
startupTimeout 30 Maximum time in seconds to wait for chrome to start
userAgent none User agent to use for the whole browser (see page API for alternative)
userDataDir none Chrome user data dir (default: a new empty dir is generated temporarily)
userCrashDumpsDir none The directory crashpad should store dumps in (crash reporter will be enabled automatically)
windowSize none Size of the window. usage: $width, $height — see also Page::setViewport

This example shows how to share a single instance of chrome for multiple scripts.

The first time the script is started we use the browser factory in order to start chrome, afterwards we save the uri to connect to this browser in the file system.

The next calls to the script will read the uri from that file in order to connect to the chrome instance instead of creating a new one. If chrome was closed or crashed, a new instance is started again.

use \HeadlessChromium\BrowserFactory; use \HeadlessChromium\Exception\BrowserConnectionFailed; // path to the file to store websocket's uri $socket = \file_get_contents('/tmp/chrome-php-demo-socket'); try < $browser = BrowserFactory::connectToBrowser($socket); > catch (BrowserConnectionFailed $e) < // The browser was probably closed, start it again $factory = new BrowserFactory(); $browser = $factory->createBrowser([ 'keepAlive' => true, ]); // save the uri to be able to connect again to browser \file_put_contents($socketFile, $browser->getSocketUri(), LOCK_EX); >

Источник

Читайте также:  Абсолютное позиционирование
Оцените статью