Playwright.pm 16 KB

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