PlaywrightPHP

Differences

Differences between PlaywrightPHP and Playwright

Playwright's class must be instantiated

Instead of requiring Playwright:

const playwright = require('playwright');

You have to instantiate the Playwright class:

$playwright = new Playwright;

This will create a new Node process controlled by PHP.

You can also pass some options to the constructor, see Rialto's documentation. PlaywrightPHP also extends these options:

[
    // Logs the output of Browser's console methods (console.log, console.debug, etc...) to the PHP logger
    'log_browser_console' => false,
]

No need to use the await keyword

With PlaywrightPHP, every method call or property getting/setting is synchronous.

Some methods have been aliased

The following methods have been aliased because PHP doesn't support the $ character in method names:

  • $ => querySelector
  • $$ => querySelectorAll
  • $x => querySelectorXPath
  • $eval => querySelectorEval
  • $$eval => querySelectorAllEval

Use these aliases just like you would have used the original methods:

$divs = $page->querySelectorAll('div');

Evaluated functions must be created with JsFunction

Functions evaluated in the context of the page must be written with the JsFunction class, the body of these functions must be written in JavaScript instead of PHP.

use Nesk\Rialto\Data\JsFunction;
 
$pageFunction = new JsFunction(['element'], "return element.textContent");

Exceptions must be caught with ->tryCatch

If an error occurs in Node, a Node\FatalException will be thrown and the process closed, you will have to create a new instance of Playwright.

To avoid that, you can ask Node to catch these errors by prepending your instruction with ->tryCatch:

use Nesk\Rialto\Exceptions\Node;
 
try {
    $page->tryCatch->goto('invalid_url');
} catch (Node\Exception $exception) {
    // Handle the exception...
}

Instead, a Node\Exception will be thrown, the Node process will stay alive and usable.

On this page