Playwright.pm 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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::ShareDir();
  8. use File::Basename();
  9. use Cwd();
  10. use LWP::UserAgent();
  11. use Sub::Install();
  12. use Net::EmptyPort();
  13. use JSON::MaybeXS();
  14. use File::Which();
  15. use Capture::Tiny qw{capture_merged capture_stderr};
  16. use Carp qw{confess};
  17. use Playwright::Base();
  18. use Playwright::Util();
  19. # Stuff closet full of skeletons at BEGIN time
  20. use Playwright::ModuleList();
  21. no warnings 'experimental';
  22. use feature qw{signatures};
  23. =head1 SYNOPSIS
  24. use Playwright;
  25. my $handle = Playwright->new();
  26. my $browser = $handle->launch( headless => 0, type => 'chrome' );
  27. my $page = $browser->newPage();
  28. my $res = $page->goto('http://somewebsite.test', { waitUntil => 'networkidle' });
  29. my $frameset = $page->mainFrame();
  30. my $kidframes = $frameset->childFrames();
  31. # Grab us some elements
  32. my $body = $page->select('body');
  33. # You can also get the innerText
  34. my $text = $body->textContent();
  35. $body->click();
  36. $body->screenshot();
  37. my $kids = $body->selectMulti('*');
  38. =head1 DESCRIPTION
  39. Perl interface to a lightweight node.js webserver that proxies commands runnable by Playwright.
  40. Checks and automatically installs a copy of the node dependencies in the local folder if needed.
  41. 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).
  42. See L<https://playwright.dev/versions> and drill down into your relevant version (run `npm list playwright` )
  43. for what the classes do, and their usage.
  44. All the classes mentioned there will correspond to a subclass of the Playwright namespace. For example:
  45. # ISA Playwright
  46. my $playwright = Playwright->new();
  47. # ISA Playwright::BrowserContext
  48. my $ctx = $playwright->newContext(...);
  49. # ISA Playwright::Page
  50. my $page = $ctx->newPage(...);
  51. # ISA Playwright::ElementHandle
  52. my $element = $ctx->select('body');
  53. See example.pl for a more thoroughly fleshed-out display on how to use this module.
  54. =head3 Getting Started
  55. When using the playwright module for the first time, you may be told to install node.js libraries.
  56. It should provide you with instructions which will get you working right away.
  57. However, depending on your node installation this may not work due to dependencies for node.js not being in the expected location.
  58. To fix this, you will need to update your NODE_PATH environment variable to point to the correct location.
  59. =head3 Questions?
  60. 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.
  61. L<https://aka.ms/playwright-slack>
  62. =head3 Documentation for Playwright Subclasses
  63. The documentation and names for the subclasses of Playwright follow the spec strictly:
  64. Playwright::BrowserContext => L<https://playwright.dev/docs/api/class-browsercontext>
  65. Playwright::Page => L<https://playwright.dev/docs/api/class-page>
  66. Playwright::ElementHandle => L<https://playwright.dev/docs/api/class-elementhandle>
  67. ...And so on. These classes are automatically generated during module build based on the spec hash built by playwright.
  68. See generate_api_json.sh and generate_perl_modules.pl if you are interested in how this sausage is made.
  69. You can check what methods are installed for each subclass by doing the following:
  70. use Data::Dumper;
  71. print Dumper($instance->{spec});
  72. There are two major exceptions in how things work versus the upstream Playwright documentation, detailed below in the C<Selectors> section.
  73. =head2 Selectors
  74. The selector functions have to be renamed from starting with $ for obvious reasons.
  75. The renamed functions are as follows:
  76. =over 4
  77. =item $ => select
  78. =item $$ => selectMulti
  79. =item $eval => evaluate
  80. =item $$eval => evalMulti
  81. =back
  82. These functions are present as part of the Page, Frame and ElementHandle classes.
  83. =head2 Scripts
  84. The evaluate() and evaluateHandle() functions can only be run in string mode.
  85. To maximize the usefulness of these, I have wrapped the string passed with the following function:
  86. const fun = new Function (toEval);
  87. args = [
  88. fun,
  89. ...args
  90. ];
  91. As such you can effectively treat the script string as a function body.
  92. The same restriction on only being able to pass one arg remains from the upstream:
  93. L<https://playwright.dev/docs/api/class-page#pageevalselector-pagefunction-arg>
  94. You will have to refer to the arguments array as described here:
  95. L<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments>
  96. You can also pass Playwright::ElementHandle objects as returned by the select() and selectMulti() routines.
  97. They will be correctly translated into DOMNodes as you would get from the querySelector() javascript functions.
  98. Calling evaluate() and evaluateHandle() on Playwright::Element objects will automatically pass the DOMNode as the first argument to your script.
  99. See below for an example of doing this.
  100. =head3 example of evaluate()
  101. # Read the console
  102. $page->on('console',"return [...arguments]");
  103. my $promise = $page->waitForEvent('console');
  104. #TODO This request can race, the server framework I use to host the playwright spec is *not* FIFO (YET)
  105. sleep 1;
  106. $page->evaluate("console.log('hug')");
  107. my $console_log = $handle->await( $promise );
  108. print "Logged to console: '".$console_log->text()."'\n";
  109. # Convenient usage of evaluate on ElementHandles
  110. # We pass the element itself as the first argument to the JS arguments array for you
  111. $element->evaluate('arguments[0].style.backgroundColor = "#FF0000"; return 1;');
  112. =head2 Asynchronous operations
  113. The waitFor* methods defined on various classes fork and exec, waiting on the promise to complete.
  114. You will need to wait on the result of the backgrounded action with the await() method documented below.
  115. # Assuming $handle is a Playwright object
  116. my $async = $page->waitForEvent('console');
  117. $page->evaluate('console.log("whee")');
  118. my $result = $handle->await( $async );
  119. my $logged = $result->text();
  120. =head2 Getting Object parents
  121. Some things, like elements naturally are children of the pages in which they are found.
  122. Sometimes this can get confusing when you are using multiple pages, especially if you let the ref to the page go out of scope.
  123. Don't worry though, you can access the parent attribute on most Playwright::* objects:
  124. # Assuming $element is a Playwright::ElementHandle
  125. my $page = $element->{parent};
  126. =head2 Firefox Specific concerns
  127. By default, firefox will open PDFs in a pdf.js window.
  128. 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():
  129. # Assuming $handle is a Playwright object
  130. my $browser = $handle->launch( type => 'firefox', firefoxUserPrefs => { 'pdfjs.disabled' => JSON::true } );
  131. =head2 Leaving browsers alive for manual debugging
  132. Passing the cleanup => 0 parameter to new() will prevent DESTROY() from cleaning up the playwright server when a playwright object goes out of scope.
  133. Be aware that this will prevent debug => 1 from printing extra messages from playwright_server itself, as we redirect the output streams in this case so as not to fill your current session with prints later.
  134. A convenience script has been provided to clean up these orphaned instances, `reap_playwright_servers` which will kill all extant `playwright_server` processes.
  135. =head1 INSTALLATION NOTE
  136. If you install this module from CPAN, you will likely encounter a croak() telling you to install node module dependencies.
  137. Follow the instructions and things should be just fine.
  138. If you aren't, please file a bug!
  139. =head1 CONSTRUCTOR
  140. =head2 new(HASH) = (Playwright)
  141. Creates a new browser and returns a handle to interact with it.
  142. =head3 INPUT
  143. debug (BOOL) : Print extra messages from the Playwright server process. Default: false
  144. timeout (INTEGER) : Seconds to wait for the playwright server to spin up and down. Default: 30s
  145. cleanup (BOOL) : Whether or not to clean up the playwright server when this object goes out of scope. Default: true
  146. =cut
  147. our ( $spec, $server_bin, $node_bin, %mapper );
  148. sub _check_node {
  149. # Check that node is installed
  150. $node_bin = File::Which::which('node');
  151. confess("node must exist, be in your PATH and executable") unless $node_bin && -x $node_bin;
  152. my $path2here = File::Basename::dirname( Cwd::abs_path( $INC{'Playwright.pm'} ) );
  153. # Make sure it's possible to start the server
  154. $server_bin = File::Which::which('playwright_server');
  155. confess("Can't locate playwright_server!
  156. Please ensure it is installed in your PATH.
  157. If you installed this module from CPAN, it should already be.")
  158. unless $server_bin && -x $server_bin;
  159. # Attempt to start the server. If we can't do this, we almost certainly have dependency issues.
  160. my ($output) = capture_merged { system($node_bin, $server_bin, '--check') };
  161. return if $output =~ m/OK/;
  162. warn $output if $output;
  163. confess( "playwright_server could not run successfully.
  164. See the above error message for why.
  165. It's likely to be unmet dependencies, or a NODE_PATH issue.
  166. Install of node dependencies must be done manually.
  167. Run the following:
  168. npm i express playwright uuid
  169. sudo npx playwright install-deps
  170. export NODE_PATH=\"\$(pwd)/node_modules\".
  171. If you still experience issues, run the following:
  172. NODE_DEBUG=module playwright_server --check
  173. This should tell you why node can't find the deps you have installed.
  174. ");
  175. }
  176. sub _build_classes {
  177. foreach my $class ( keys(%$spec) ) {
  178. $mapper{$class} = sub {
  179. my ( $self, $res ) = @_;
  180. my $class = "Playwright::$class";
  181. return $class->new(
  182. handle => $self,
  183. id => $res->{_guid},
  184. type => $class,
  185. parent => $self,
  186. );
  187. };
  188. }
  189. }
  190. sub BEGIN {
  191. our $SKIP_BEGIN;
  192. _check_node() unless $SKIP_BEGIN;
  193. }
  194. sub new ( $class, %options ) {
  195. #XXX yes, this is a race, so we need retries in _start_server
  196. my $port = Net::EmptyPort::empty_port();
  197. my $timeout = $options{timeout} // 30;
  198. my $self = bless(
  199. {
  200. ua => $options{ua} // LWP::UserAgent->new(),
  201. port => $port,
  202. debug => $options{debug},
  203. cleanup => $options{cleanup} // 1,
  204. pid => _start_server( $port, $timeout, $options{debug}, $options{cleanup} // 1 ),
  205. parent => $$,
  206. timeout => $timeout,
  207. },
  208. $class
  209. );
  210. $self->_check_and_build_spec();
  211. _build_classes();
  212. return $self;
  213. }
  214. sub _check_and_build_spec ($self) {
  215. return $spec if ref $spec eq 'HASH';
  216. $spec = Playwright::Util::request(
  217. 'GET', 'spec', $self->{port}, $self->{ua},
  218. );
  219. confess("Could not retrieve Playwright specification. Check that your playwright installation is correct and complete.") unless ref $spec eq 'HASH';
  220. return $spec;
  221. }
  222. =head1 METHODS
  223. =head2 launch(HASH) = Playwright::Browser
  224. The Argument hash here is essentially those you'd see from browserType.launch(). See:
  225. L<https://playwright.dev/docs/api/class-browsertype#browsertypelaunchoptions>
  226. There is an additional "special" argument, that of 'type', which is used to specify what type of browser to use, e.g. 'firefox'.
  227. =cut
  228. sub launch ( $self, %args ) {
  229. Playwright::Base::_coerce(
  230. $spec->{BrowserType}{members},
  231. args => [ \%args ],
  232. command => 'launch'
  233. );
  234. delete $args{command};
  235. my $msg = Playwright::Util::request(
  236. 'POST', 'session', $self->{port}, $self->{ua},
  237. type => delete $args{type},
  238. args => [ \%args ]
  239. );
  240. return $Playwright::mapper{ $msg->{_type} }->( $self, $msg )
  241. if ( ref $msg eq 'HASH' )
  242. && $msg->{_type}
  243. && exists $Playwright::mapper{ $msg->{_type} };
  244. return $msg;
  245. }
  246. =head2 await (HASH) = Object
  247. Waits for an asynchronous operation returned by the waitFor* methods to complete and returns the value.
  248. =cut
  249. sub await ( $self, $promise ) {
  250. my $obj = Playwright::Util::await($promise);
  251. return $obj unless $obj->{_type};
  252. my $class = "Playwright::$obj->{_type}";
  253. return $class->new(
  254. type => $obj->{_type},
  255. id => $obj->{_guid},
  256. handle => $self
  257. );
  258. }
  259. =head2 quit, DESTROY
  260. Terminate the browser session and wait for the Playwright server to terminate.
  261. Automatically called when the Playwright object goes out of scope.
  262. =cut
  263. sub quit ($self) {
  264. # Prevent double destroy after quit()
  265. return if $self->{killed};
  266. # Prevent destructor from firing in child processes so we can do things like async()
  267. # This should also prevent the waitpid below from deadlocking due to two processes waiting on the same pid.
  268. return unless $$ == $self->{parent};
  269. # Prevent destructor from firing in the event the caller instructs it to not fire
  270. return unless $self->{cleanup};
  271. # Make sure we don't mash the exit code of things like prove
  272. local $?;
  273. $self->{killed} = 1;
  274. print "Attempting to terminate server process...\n" if $self->{debug};
  275. Playwright::Util::request( 'GET', 'shutdown', $self->{port}, $self->{ua} );
  276. # 0 is always WCONTINUED, 1 is always WNOHANG, and POSIX is an expensive import
  277. # When 0 is returned, the process is still active, so it needs more persuasion
  278. foreach (0..3) {
  279. return unless waitpid( $self->{pid}, 1) == 0;
  280. sleep 1;
  281. }
  282. # Advanced persuasion
  283. print "Forcibly terminating server process...\n" if $self->{debug};
  284. kill('TERM', $self->{pid});
  285. #XXX unfortunately I can't just do a SIGALRM, because blocking system calls can't be intercepted on win32
  286. foreach (0..$self->{timeout}) {
  287. return unless waitpid( $self->{pid}, 1 ) == 0;
  288. sleep 1;
  289. }
  290. warn "Could not shut down playwright server!";
  291. return;
  292. }
  293. sub DESTROY ($self) {
  294. $self->quit();
  295. }
  296. sub _start_server ( $port, $timeout, $debug, $cleanup ) {
  297. $debug = $debug ? '-d' : '';
  298. $ENV{DEBUG} = 'pw:api' if $debug;
  299. my $pid = fork // confess("Could not fork");
  300. if ($pid) {
  301. print "Waiting for port to come up...\n" if $debug;
  302. Net::EmptyPort::wait_port( $port, $timeout )
  303. or confess("Server never came up after 30s!");
  304. print "done\n" if $debug;
  305. return $pid;
  306. }
  307. # Orphan the process in the event that cleanup => 0
  308. if (!$cleanup) {
  309. print "Detaching child process...\n";
  310. chdir '/';
  311. require POSIX;
  312. die "Cannot detach playwright_server process for persistence" if POSIX::setsid() < 0;
  313. require Capture::Tiny;
  314. capture_merged { exec( $node_bin, $server_bin, "--port", $port, $debug ) };
  315. die("Could not exec!");
  316. }
  317. exec( $node_bin, $server_bin, "--port", $port, $debug );
  318. }
  319. 1;