Playwright.pm 16 KB

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