Playwright.pm 14 KB

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