如何从PHP执行PhantomJS

时间:2013-11-25 20:16:27

标签: javascript php phantomjs php-phantomjs

我想在localhost上从PHP执行PhantomJS。

任何机构都可以解释如何从PHP执行PhantomJS以及我应该从phantomjs.org下载什么软件包?

3 个答案:

答案 0 :(得分:27)

  • 下载PhantomJS binary,将其上传到某处并使其可执行(chmod +x
  • 如果您要制作屏幕截图,请设置fontconfig(这非常特定于我的配置,但目标是确保系统中至少包含一些字体)
  • 在PHP中运行以下内容:
    $response = exec('/path/to/phantomjs myscript.js');

答案 1 :(得分:8)

实际上有一个名为PHP PhantomJS的库,旨在让您更轻松!

  

PHP PhantomJS是一个灵活的PHP库,可以通过它加载页面   PhantomJS无头浏览器并返回页面响应。它很方便   用于测试需要javascript支持并且还支持的网站   屏幕截图。

     

Full documentation

功能列表:

  
      
  • 通过PhantomJS无头浏览器加载网页
  •   
  • 查看详细的回复数据,包括页面内容,标题,状态代码等。
  •   
  • 处理重定向
  •   
  • 查看javascript控制台错误
  •   
  • 查看详细的PhantomJS调试信息
  •   
  • 将屏幕截图保存到本地磁盘
  •   
  • 设置视口大小
  •   
  • 定义屏幕捕获x,y,宽度和高度参数
  •   
  • 延迟指定时间的页面呈现
  •   
  • 使用命令行选项执行PhantomJS
  •   
  • 轻松构建和运行自定义PhantomJS脚本
  •   

请确保您的 PhantomJS 版本与您的 PHP PhantomJS 版本兼容:

  

请注意:此库的4.0版目前正在等待   PhantomJS 2.0尚未解决的问题。

答案 2 :(得分:2)

我最近发布了一个项目,可以让PHP访问浏览器。在此处获取:https://github.com/merlinthemagic/MTS。在引擎盖下,它依赖于PhantomJS。

下载并设置后,您只需使用以下代码:

$myUrl          = "http://www.example.com";
$windowObj      = \MTS\Factories::getDevices()->getLocalHost()->getBrowser('phantomjs')->getNewWindow($myUrl);

//now you can either retrive the DOM and parse it, like this:
$domData    = $windowObj->getDom();

//or take screen shots
$imageData    = $windowObj->screenshot();

//or use the mouse to click buttons:
$windowObj->mouseEventOnElement("[id=searchInput]", 'leftclick');

//or type with the keyboard :
$windowObj->sendKeyPresses("my search words");

//or load and execute custom javascript, fill forms etc, etc.
相关问题