Playwright.pm 16 KB

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