Playwright.pm 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. package Playwright;
  2. use strict;
  3. use warnings;
  4. #ABSTRACT: Perl client for Playwright
  5. use 5.006;
  6. use v5.28.0; # Before 5.006, v5.10.0 would not be understood.
  7. use File::pushd;
  8. use File::ShareDir();
  9. use File::Basename();
  10. use Cwd();
  11. use LWP::UserAgent();
  12. use Sub::Install();
  13. use Net::EmptyPort();
  14. use JSON::MaybeXS();
  15. use File::Which();
  16. use Capture::Tiny qw{capture_merged capture_stderr};
  17. use Carp qw{confess};
  18. use Playwright::Base();
  19. use Playwright::Util();
  20. no warnings 'experimental';
  21. use feature qw{signatures};
  22. =head1 SYNOPSIS
  23. use Playwright;
  24. my $handle = Playwright->new();
  25. my $browser = $handle->launch( headless => 0, type => 'chrome' );
  26. my $page = $browser->newPage();
  27. my $res = $page->goto('http://somewebsite.test', { waitUntil => 'networkidle' });
  28. my $frameset = $page->mainFrame();
  29. my $kidframes = $frameset->childFrames();
  30. # Grab us some elements
  31. my $body = $page->select('body');
  32. # You can also get the innerText
  33. my $text = $body->textContent();
  34. $body->click();
  35. $body->screenshot();
  36. my $kids = $body->selectMulti('*');
  37. =head1 DESCRIPTION
  38. Perl interface to a lightweight node.js webserver that proxies commands runnable by Playwright.
  39. Checks and automatically installs a copy of the node dependencies in the local folder if needed.
  40. Currently understands commands you can send to all the playwright classes defined in api.json (installed wherever your OS puts shared files for CPAN distributions).
  41. See L<https://playwright.dev/versions> and drill down into your relevant version (run `npm list playwright` )
  42. for what the classes do, and their usage.
  43. All the classes mentioned there will correspond to a subclass of the Playwright namespace. For example:
  44. # ISA Playwright
  45. my $playwright = Playwright->new();
  46. # ISA Playwright::BrowserContext
  47. my $ctx = $playwright->newContext(...);
  48. # ISA Playwright::Page
  49. my $page = $ctx->newPage(...);
  50. # ISA Playwright::ElementHandle
  51. my $element = $ctx->select('body');
  52. See example.pl for a more thoroughly fleshed-out display on how to use this module.
  53. =head3 Questions?
  54. Feel free to join the Playwright slack server, as there is a dedicated #playwright-perl channel which I, the module author, await your requests in.
  55. L<https://aka.ms/playwright-slack>
  56. =head3 Why this documentation does not list all available subclasses and their methods
  57. The documentation and names for the subclasses of Playwright follow the spec strictly:
  58. Playwright::BrowserContext => L<https://playwright.dev/docs/api/class-browsercontext>
  59. Playwright::Page => L<https://playwright.dev/docs/api/class-page>
  60. Playwright::ElementHandle => L<https://playwright.dev/docs/api/class-elementhandle>
  61. ...And so on. 100% of the spec is accessible regardless of the Playwright version installed
  62. due to these classes & their methods being built dynamically at run time based on the specification
  63. which is shipped with Playwright itself.
  64. You can check what methods are installed for each subclass by doing the following:
  65. use Data::Dumper;
  66. print Dumper($instance->{spec});
  67. There are two major exceptions in how things work versus the upstream Playwright documentation, detailed below in the C<Selectors> section.
  68. =head2 Selectors
  69. The selector functions have to be renamed from starting with $ for obvious reasons.
  70. The renamed functions are as follows:
  71. =over 4
  72. =item $ => select
  73. =item $$ => selectMulti
  74. =item $eval => eval
  75. =item $$eval => evalMulti
  76. =back
  77. These functions are present as part of the Page, Frame and ElementHandle classes.
  78. =head2 Scripts
  79. The evaluate() and evaluateHandle() functions can only be run in string mode.
  80. To maximize the usefulness of these, I have wrapped the string passed with the following function:
  81. const fun = new Function (toEval);
  82. args = [
  83. fun,
  84. ...args
  85. ];
  86. As such you can effectively treat the script string as a function body.
  87. The same restriction on only being able to pass one arg remains from the upstream:
  88. L<https://playwright.dev/docs/api/class-page#pageevalselector-pagefunction-arg>
  89. You will have to refer to the arguments array as described here:
  90. L<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments>
  91. =head3 example of evaluate()
  92. # Read the console
  93. $page->on('console',"return [...arguments]");
  94. my $promise = $page->waitForEvent('console');
  95. #TODO This request can race, the server framework I use to host the playwright spec is *not* FIFO (YET)
  96. sleep 1;
  97. $page->evaluate("console.log('hug')");
  98. my $console_log = $handle->await( $promise );
  99. print "Logged to console: '".$console_log->text()."'\n";
  100. =head2 Asynchronous operations
  101. The waitFor* methods defined on various classes are essentially a light wrapper around Mojo::IOLoop::Subprocess.
  102. You will need to wait on the result of the backgrounded action with the await() method documented below.
  103. # Assuming $handle is a Playwright object
  104. my $async = $page->waitForEvent('console');
  105. $page->evaluate('console.log("whee")');
  106. my $result = $handle->await( $async );
  107. my $logged = $result->text();
  108. =head2 Getting Object parents
  109. Some things, like elements naturally are children of the pages in which they are found.
  110. Sometimes this can get confusing when you are using multiple pages, especially if you let the ref to the page go out of scope.
  111. Don't worry though, you can access the parent attribute on most Playwright::* objects:
  112. # Assuming $element is a Playwright::ElementHandle
  113. my $page = $element->{parent};
  114. =head2 Firefox Specific concerns
  115. By default, firefox will open PDFs in a pdf.js window.
  116. To suppress this behavior (such as in the event you are await()ing a download event), you will have to pass this option to launch():
  117. # Assuming $handle is a Playwright object
  118. my $browser = $handle->launch( type => 'firefox', firefoxUserPrefs => { 'pdfjs.disabled' => JSON::true } );
  119. =head1 INSTALLATION NOTE
  120. If you install this module from CPAN, you will likely encounter a croak() telling you to install node module dependencies.
  121. Follow the instructions and things should be just fine.
  122. If you aren't, please file a bug!
  123. =head1 CONSTRUCTOR
  124. =head2 new(HASH) = (Playwright)
  125. Creates a new browser and returns a handle to interact with it.
  126. =head3 INPUT
  127. debug (BOOL) : Print extra messages from the Playwright server process
  128. timeout (INTEGER) : Seconds to wait for the playwright server to spin up and down. Default: 30s
  129. =cut
  130. our ( $spec, $server_bin, $node_bin, %mapper, %methods_to_rename );
  131. sub _check_node {
  132. # Check that node is installed
  133. $node_bin = File::Which::which('node');
  134. confess("node must exist, be in your PATH and executable") unless $node_bin && -x $node_bin;
  135. my $global_install = '';
  136. my $path2here = File::Basename::dirname( Cwd::abs_path( $INC{'Playwright.pm'} ) );
  137. # Make sure it's possible to start the server
  138. $server_bin = "$path2here/../bin/playwright_server";
  139. if (!-f $server_bin ) {
  140. $server_bin = File::Which::which('playwright_server');
  141. $global_install = 1;
  142. }
  143. confess("Can't locate Playwright server in '$server_bin'!")
  144. unless -f $server_bin;
  145. # Attempt to start the server. If we can't do this, we almost certainly have dependency issues.
  146. my ($output) = capture_merged { system($node_bin, $server_bin, '--check') };
  147. return if $output =~ m/OK/;
  148. # Check for the necessary modules, this relies on package.json
  149. my $npm_bin = File::Which::which('npm');
  150. confess("npm must exist and be executable") unless -x $npm_bin;
  151. # pushd/popd closure
  152. {
  153. my $curdir = pushd(File::Basename::dirname($server_bin));
  154. # Attempt to install deps automatically.
  155. confess("Production install of node dependencies must be done manually by nonroot users. Run the following:\n\n pushd '$curdir' && sudo npm i yargs express playwright uuid; popd\n\n") if $global_install;
  156. my $err = capture_stderr { qx{npm i} };
  157. # XXX apparently doing it 'once more with feeling' fixes issues on windows, lol
  158. $err = capture_stderr { qx{npm i} };
  159. my $exit = $? >> 8;
  160. # Ignore failing for bogus reasons
  161. if ( $err !~ m/package-lock/ ) {
  162. confess("Error installing node dependencies:\n$err") if $exit;
  163. }
  164. }
  165. }
  166. sub _build_classes {
  167. $mapper{mouse} = sub {
  168. my ( $self, $res ) = @_;
  169. return Playwright::Mouse->new(
  170. handle => $self,
  171. id => $res->{_guid},
  172. type => 'Mouse'
  173. );
  174. };
  175. $mapper{keyboard} = sub {
  176. my ( $self, $res ) = @_;
  177. return Playwright::Keyboard->new(
  178. handle => $self,
  179. id => $res->{_guid},
  180. type => 'Keyboard'
  181. );
  182. };
  183. %methods_to_rename = (
  184. '$' => 'select',
  185. '$$' => 'selectMulti',
  186. '$eval' => 'eval',
  187. '$$eval' => 'evalMulti',
  188. );
  189. foreach my $class ( keys(%$spec) ) {
  190. $mapper{$class} = sub {
  191. my ( $self, $res ) = @_;
  192. my $class = "Playwright::$class";
  193. return $class->new(
  194. handle => $self,
  195. id => $res->{_guid},
  196. type => $class,
  197. parent => $self,
  198. );
  199. };
  200. #All of the Playwright::* Classes are made by this MAGIC
  201. Sub::Install::install_sub(
  202. {
  203. code => sub ( $classname, %options ) {
  204. @class::ISA = qw{Playwright::Base};
  205. $options{type} = $class;
  206. return Playwright::Base::new( $classname, %options );
  207. },
  208. as => 'new',
  209. into => "Playwright::$class",
  210. }
  211. ) unless "Playwright::$class"->can('new');;
  212. # Hack in mouse and keyboard objects for the Page class
  213. if ( $class eq 'Page' ) {
  214. foreach my $hid (qw{keyboard mouse}) {
  215. Sub::Install::install_sub(
  216. {
  217. code => sub {
  218. my $self = shift;
  219. $Playwright::mapper{$hid}->(
  220. $self,
  221. {
  222. _type => $self->{type},
  223. _guid => $self->{guid}
  224. }
  225. ) if exists $Playwright::mapper{$hid};
  226. },
  227. as => $hid,
  228. into => "Playwright::$class",
  229. }
  230. ) unless "Playwright::$class"->can($hid);
  231. }
  232. }
  233. # Install the subroutines if they aren't already
  234. foreach my $method ( ( keys( %{ $spec->{$class}{members} } ), 'on' ) ) {
  235. next if grep { $_ eq $method } qw{keyboard mouse};
  236. my $renamed =
  237. exists $methods_to_rename{$method}
  238. ? $methods_to_rename{$method}
  239. : $method;
  240. Sub::Install::install_sub(
  241. {
  242. code => sub {
  243. my $self = shift;
  244. Playwright::Base::_request(
  245. $self,
  246. args => [@_],
  247. command => $method,
  248. object => $self->{guid},
  249. type => $self->{type}
  250. );
  251. },
  252. as => $renamed,
  253. into => "Playwright::$class",
  254. }
  255. ) unless "Playwright::$class"->can($renamed);
  256. }
  257. }
  258. }
  259. sub BEGIN {
  260. our $SKIP_BEGIN;
  261. _check_node() unless $SKIP_BEGIN;
  262. }
  263. sub new ( $class, %options ) {
  264. #XXX yes, this is a race, so we need retries in _start_server
  265. my $port = Net::EmptyPort::empty_port();
  266. my $timeout = $options{timeout} // 30;
  267. my $self = bless(
  268. {
  269. ua => $options{ua} // LWP::UserAgent->new(),
  270. port => $port,
  271. debug => $options{debug},
  272. pid => _start_server( $port, $timeout, $options{debug} ),
  273. parent => $$,
  274. timeout => $timeout,
  275. },
  276. $class
  277. );
  278. $self->_check_and_build_spec();
  279. _build_classes();
  280. return $self;
  281. }
  282. sub _check_and_build_spec ($self) {
  283. return $spec if ref $spec eq 'HASH';
  284. $spec = Playwright::Util::request(
  285. 'GET', 'spec', $self->{port}, $self->{ua},
  286. );
  287. confess("Could not retrieve Playwright specification. Check that your playwright installation is correct and complete.") unless ref $spec eq 'HASH';
  288. return $spec;
  289. }
  290. =head1 METHODS
  291. =head2 launch(HASH) = Playwright::Browser
  292. The Argument hash here is essentially those you'd see from browserType.launch(). See:
  293. L<https://playwright.dev/docs/api/class-browsertype#browsertypelaunchoptions>
  294. There is an additional "special" argument, that of 'type', which is used to specify what type of browser to use, e.g. 'firefox'.
  295. =cut
  296. sub launch ( $self, %args ) {
  297. Playwright::Base::_coerce(
  298. $spec->{BrowserType}{members},
  299. args => [ \%args ],
  300. command => 'launch'
  301. );
  302. delete $args{command};
  303. my $msg = Playwright::Util::request(
  304. 'POST', 'session', $self->{port}, $self->{ua},
  305. type => delete $args{type},
  306. args => [ \%args ]
  307. );
  308. return $Playwright::mapper{ $msg->{_type} }->( $self, $msg )
  309. if ( ref $msg eq 'HASH' )
  310. && $msg->{_type}
  311. && exists $Playwright::mapper{ $msg->{_type} };
  312. return $msg;
  313. }
  314. =head2 await (HASH) = Object
  315. Waits for an asynchronous operation returned by the waitFor* methods to complete and returns the value.
  316. =cut
  317. sub await ( $self, $promise ) {
  318. my $obj = Playwright::Util::await($promise);
  319. return $obj unless $obj->{_type};
  320. my $class = "Playwright::$obj->{_type}";
  321. return $class->new(
  322. type => $obj->{_type},
  323. id => $obj->{_guid},
  324. handle => $self
  325. );
  326. }
  327. =head2 quit, DESTROY
  328. Terminate the browser session and wait for the Playwright server to terminate.
  329. Automatically called when the Playwright object goes out of scope.
  330. =cut
  331. sub quit ($self) {
  332. # Prevent double destroy after quit()
  333. return if $self->{killed};
  334. # Prevent destructor from firing in child processes so we can do things like async()
  335. # This should also prevent the waitpid below from deadlocking due to two processes waiting on the same pid.
  336. return unless $$ == $self->{parent};
  337. # Make sure we don't mash the exit code of things like prove
  338. local $?;
  339. $self->{killed} = 1;
  340. print "Attempting to terminate server process...\n" if $self->{debug};
  341. Playwright::Util::request( 'GET', 'shutdown', $self->{port}, $self->{ua} );
  342. # 0 is always WCONTINUED, 1 is always WNOHANG, and POSIX is an expensive import
  343. # When 0 is returned, the process is still active, so it needs more persuasion
  344. foreach (0..3) {
  345. return unless waitpid( $self->{pid}, 1) == 0;
  346. sleep 1;
  347. }
  348. # Advanced persuasion
  349. print "Forcibly terminating server process...\n" if $self->{debug};
  350. kill('TERM', $self->{pid});
  351. #XXX unfortunately I can't just do a SIGALRM, because blocking system calls can't be intercepted on win32
  352. foreach (0..$self->{timeout}) {
  353. return unless waitpid( $self->{pid}, 1 ) == 0;
  354. sleep 1;
  355. }
  356. warn "Could not shut down playwright server!";
  357. return;
  358. }
  359. sub DESTROY ($self) {
  360. $self->quit();
  361. }
  362. sub _start_server ( $port, $timeout, $debug ) {
  363. $debug = $debug ? '-d' : '';
  364. $ENV{DEBUG} = 'pw:api' if $debug;
  365. my $pid = fork // confess("Could not fork");
  366. if ($pid) {
  367. print "Waiting for port to come up...\n" if $debug;
  368. Net::EmptyPort::wait_port( $port, $timeout )
  369. or confess("Server never came up after 30s!");
  370. print "done\n" if $debug;
  371. return $pid;
  372. }
  373. exec( $node_bin, $server_bin, "-p", $port, $debug );
  374. }
  375. 1;