example.pl 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. use strict;
  2. use warnings;
  3. use Data::Dumper;
  4. use JSON::PP;
  5. use Async;
  6. use Playwright;
  7. use Try::Tiny;
  8. my $handle = Playwright->new( debug => 1 );
  9. # Open a new chrome instance
  10. my $browser = $handle->launch( headless => JSON::PP::false, type => 'chrome' );
  11. # Open a tab therein
  12. my $page = $browser->newPage({ videosPath => 'video' });
  13. my $bideo = $page->video;
  14. my $vidpath = $bideo->path;
  15. print "Video Path: $vidpath\n";
  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://google.com', { 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. #XXX this is unfortunately stringifying this object
  42. my $proc = Async->new( sub {
  43. return $page->waitForEvent('console');
  44. });
  45. $page->evaluate("console.log('hug')");
  46. my $console_log = $proc->result(1);
  47. use Data::Dumper;
  48. print Dumper($console_log);
  49. #print "Logged to console: '".$console_log->text()."'\n";
  50. # Use a selector to find which input is visible and type into it
  51. # Ideally you'd use a better selector to solve this problem, but this is just showing off
  52. my $inputs = $page->selectMulti('input');
  53. foreach my $input (@$inputs) {
  54. try {
  55. # Pretty much a brute-force approach here, again use a better pseudo-selector instead like :visible
  56. $input->fill('tickle', { timeout => 250 } );
  57. } catch {
  58. print "Element not visible, skipping...\n";
  59. }
  60. }
  61. # Said better selector
  62. my $actual_input = $page->select('input[name=q]');
  63. $actual_input->fill('whee');
  64. # Take screen of said element
  65. $actual_input->screenshot({ path => 'test.jpg' });
  66. # Fiddle with HIDs
  67. my $mouse = $page->mouse;
  68. print "GOT HERE\n";
  69. $mouse->move( 0, 0 );
  70. my $keyboard = $page->keyboard();
  71. $keyboard->type('F12');