example.pl 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. use strict;
  2. use warnings;
  3. use Data::Dumper;
  4. use Playwright;
  5. use Try::Tiny;
  6. {
  7. my $handle = Playwright->new( debug => 1 );
  8. # Open a new chrome instance
  9. my $browser = $handle->launch( headless => 1, type => 'firefox' );
  10. my $process = $handle->server( browser => $browser, command => 'process' );
  11. print "Browser PID: ".$process->{pid}."\n";
  12. # Open a tab therein
  13. my $page = $browser->newPage({ videosPath => 'video', acceptDownloads => 1 });
  14. # Test the spec method
  15. print Dumper($page->spec(),$page);
  16. # Browser contexts don't exist until you open at least one page.
  17. # You'll need this to grab and set cookies.
  18. my ($context) = @{$browser->contexts()};
  19. # Load a URL in the tab
  20. my $res = $page->goto('http://troglodyne.net', { waitUntil => 'networkidle' });
  21. print Dumper($res->status(), $browser->version());
  22. # Put your hand in the jar
  23. my $cookies = $context->cookies();
  24. print Dumper($cookies);
  25. # Grab the main frame, in case this is a frameset
  26. my $frameset = $page->mainFrame();
  27. print Dumper($frameset->childFrames());
  28. # Run some JS
  29. my $fun = "
  30. var input = arguments[0];
  31. return {
  32. width: document.documentElement.clientWidth,
  33. height: document.documentElement.clientHeight,
  34. deviceScaleFactor: window.devicePixelRatio,
  35. arg: input
  36. };";
  37. my $result = $page->evaluate($fun, 'zippy');
  38. print Dumper($result);
  39. # Read the console
  40. $page->on('console',"return [...arguments]");
  41. my $promise = $page->waitForEvent('console');
  42. #XXX this *can* race
  43. sleep 1;
  44. $page->evaluate("console.log('hug')");
  45. my $console_log = $handle->await( $promise );
  46. print "Logged to console: '".$console_log->text()."'\n";
  47. # Use a selector to find which input is visible and type into it
  48. # Ideally you'd use a better selector to solve this problem, but this is just showing off
  49. my $inputs = $page->selectMulti('input');
  50. foreach my $input (@$inputs) {
  51. try {
  52. # Pretty much a brute-force approach here, again use a better pseudo-selector instead like :visible
  53. $input->fill('tickle', { timeout => 250 } );
  54. } catch {
  55. print "Element not visible, skipping...\n";
  56. }
  57. }
  58. # Said better selector
  59. my $actual_input = $page->select('input[name=like]');
  60. $actual_input->fill('whee');
  61. # Ensure we can grab the parent (convenience)
  62. print "Got Parent: ISA ".ref($actual_input->{parent})."\n";
  63. # Take screen of said element
  64. $actual_input->screenshot({ path => 'test.jpg' });
  65. # Fiddle with HIDs
  66. my $mouse = $page->mouse;
  67. $mouse->move( 0, 0 );
  68. my $keyboard = $page->keyboard();
  69. $keyboard->type('F12');
  70. # Start to do some more advanced actions with the page
  71. use FindBin;
  72. use Cwd qw{abs_path};
  73. my $pg = abs_path("$FindBin::Bin/at/test.html");
  74. # Handle dialogs on page start, and dialog after dialog
  75. # NOTE -- the 'load' event won't fire until the dialog is dismissed in some browsers
  76. $promise = $page->waitForEvent('dialog');
  77. $page->goto("file://$pg", { waitUntil => 'networkidle' });
  78. my $dlg = $handle->await($promise);
  79. $promise = $page->waitForEvent('dialog');
  80. $dlg->dismiss();
  81. $dlg = $handle->await($promise);
  82. $dlg->accept();
  83. # Download stuff -- note this requries acceptDownloads = true in the page open
  84. # NOTE -- the 'download' event fires unreliably, as not all browsers properly obey the 'download' property in hrefs.
  85. # Chrome, for example would choke here on an intermediate dialog.
  86. $promise = $page->waitForEvent('download');
  87. $page->select('#d-lo')->click();
  88. my $download = $handle->await( $promise );
  89. print "Download suggested filename\n";
  90. print $download->suggestedFilename()."\n";
  91. $download->saveAs('test2.jpg');
  92. # Fiddle with file inputs
  93. my $choochoo = $page->waitForEvent('filechooser');
  94. $page->select('#drphil')->click();
  95. my $chooseu = $handle->await( $choochoo );
  96. $chooseu->setFiles('test.jpg');
  97. # Make sure we can do child selectors
  98. my $parent = $page->select('body');
  99. my $child = $parent->select('#drphil');
  100. print ref($child)."\n";
  101. # Test out pusht/popt/try_until
  102. # Timeouts are in milliseconds
  103. Playwright::pusht($page,5000);
  104. my $checkpoint = time();
  105. my $element = Playwright::try_until($page, 'select', 'bogus-bogus-nothere');
  106. my $elapsed = time() - $checkpoint;
  107. Playwright::popt($page);
  108. print "Waited $elapsed seconds for timeout to drop\n";
  109. $checkpoint = time();
  110. $element = Playwright::try_until($page, 'select', 'bogus-bogus-nothere');
  111. $elapsed = time() - $checkpoint;
  112. print "Waited $elapsed seconds for timeout to drop\n";
  113. # Try out the API testing extensions
  114. print "HEAD http://troglodyne.net : \n";
  115. my $fr = $page->request;
  116. my $resp = $fr->fetch("http://troglodyne.net", { method => "HEAD" });
  117. print Dumper($resp->headers());
  118. print "200 OK\n" if $resp->status() == 200;
  119. # Test that we can do stuff with with the new locator API.
  120. my $loc = $page->locator('body');
  121. my $innerTubes = $loc->allInnerTexts();
  122. print Dumper($innerTubes);
  123. my $image = $page->getByAltText('picture');
  124. print Dumper($image);
  125. # Save a video now that we are done
  126. my $bideo = $page->video;
  127. # IT IS IMPORTANT TO CLOSE THE PAGE FIRST OR THIS WILL HANG!
  128. $page->close();
  129. my $vidpath = $bideo->saveAs('video/example.webm');
  130. }
  131. # Example of using persistent mode / remote hosts
  132. {
  133. my $handle = Playwright->new( debug => 1 );
  134. my $handle2 = Playwright->new( debug => 1, host => 'localhost', port => $handle->{port} );
  135. my $browser = $handle2->launch( headless => 1, type => 'firefox' );
  136. my $process = $handle2->server( browser => $browser, command => 'process' );
  137. print "Browser PID: ".$process->{pid}."\n";
  138. }
  139. # Clean up, since we left survivors
  140. require './bin/reap_playwright_servers';
  141. Playwright::ServerReaper::main();
  142. 0;