码迷,mamicode.com
首页 > Web开发 > 详细

PHP PhantomJs中文文档(翻译)

时间:2015-08-08 22:53:06      阅读:7355      评论:0      收藏:0      [点我收藏+]

标签:

介绍

PHP PhantomJS 是一个灵活的 PHP 库加载页面通过 PhantomJS 无头浏览器并将返回页面响应。这是方便于需要JavaScript的支持,同时还支持截屏测试网站。
功能列表
通过 PhantomJS 无头浏览器加载网页
查看详细的响应数据包括页面内容、 标题、 状态代码等。
处理重定向
查看 javascript 控制台错误
查看详细的 PhantomJS 的调试信息
将屏幕截图保存到本地磁盘
设置视区大小
定义屏幕截图的 x、 y、 宽度和高度参数
指定的时间的呈现延迟页
通过命令行选项执行 PhantomJS
轻松地构建并运行 自定义的PhantomJS 脚本

先决条件

PHP PhantomJS 需要 PHP 5.3.0 或更高版本运行。

安装

建议你使用Composer安装 PHP PhantomJS。首先,添加以下内容到你项目的composer.json文件:

#composer.json
 
    "scripts": {
        "post-install-cmd": [
            "PhantomInstaller\\Installer::installPhantomJS"
        ],
        "post-update-cmd": [
            "PhantomInstaller\\Installer::installPhantomJS"
        ]
    }
这将确保最新的PhantomJS版本安装在您的系统的 bin 文件夹。如果您还没有在你 composer.json 中定义你 bin 文件夹,添加路径:
 
#composer.json
    
    "config": {
        "bin-dir": "bin"
    }

最后,在您的项目的根目录安装 PHP PhantomJS:

#bash
    
    $ composer require "jonnyw/php-phantomjs:3.*"
如果你想要使用另一种安装方法,或想要查看更详细的安装说明,请参阅安装文档。


基本用法
以下内容说明了如何创建一个基本的 GET 请求和输出页面内容:
<?php
 
    use JonnyW\PhantomJs\Client;
 
    $client = Client::getInstance();
 
    /**
     * @see JonnyW\PhantomJs\Message\Request
     **/
    $request = $client->getMessageFactory()->createRequest(‘http://google.com‘, ‘GET‘);
 
    /**
     * @see JonnyW\PhantomJs\Message\Response
     **/
    $response = $client->getMessageFactory()->createResponse();
 
    // Send the request
    $client->send($request, $response);
 
    if($response->getStatus() === 200) {
 
        // Dump the requested page content
        echo $response->getContent();
    }

并且如果你想要将屏幕截图保存到本地磁盘:
<?php
 
    use JonnyW\PhantomJs\Client;
 
    $client = Client::getInstance();
 
    /**
     * @see JonnyW\PhantomJs\Message\CaptureRequest
     **/
    $request = $client->getMessageFactory()->createCaptureRequest(‘http://google.com‘, ‘GET‘);
    $request->setCaptureFile(‘/path/to/save/capture/file.jpg‘);
 
    /**
     * @see JonnyW\PhantomJs\Message\Response
     **/
    $response = $client->getMessageFactory()->createResponse();
 
    // Send the request
    $client->send($request, $response);
有关更详细的示例,请参见使用章节,或者创建自己的自定义脚本检验高级的文档。


安装
•    前提条件
•    通过Composer安装
•    自定义安装
•    从压缩文件安装
前提组件

PHP PhantomJS 需要 PHP 5.3.0 或更高版本运行。
通过Composer安装

在你的项目中安装Composer:

#bash
 
$ curl-s http://getcomposer.org/installer |php
在您的项目的根目录中创建一个 composer.json 文件:
 
#composer.json
 
{
"require": {
"jonnyw/php-phantomjs":"3"
},
"config": {
"bin-dir":"bin"
},
"scripts": {
"post-install-cmd": [
""PhantomInstaller\\Installer::installPhantomJS
],
"post-update-cmd": [
""PhantomInstaller\\Installer::installPhantomJS
]
}
}
在你的composer.json文件中有“script"部分是非常重要的,因为他将为你的系统项目安装最新版本的PhantomJS到你的bin文件夹中 。建议您创建一个 bin 文件夹在您的项目的根路径,因为将在PHP   PhantomJS库将在那里寻找PhantomJS可执行文件。如果您想在一个自定义的路径使用PhantomJS 可执行文件,请参阅自定义安装部分。

最后,为你的项目安装composer依赖:

#bash
$php composer.phar install
自定义安装

如果您希望为PhantomJS自定义安装路径,你只需要告诉客户端在哪里可以找到可执行文件:
<?php
 
use JonnyW\PhantomJs\Client;
 
$client = Client::getInstance();
 
$client->setPhantomJs(‘/path/to/phantomjs‘);
重要
PHP PhantomJS 库还需要一个通过库捆绑和被安装在你的composer.json文件中定义的bin文件夹下的phantomloader 文件。如果您要设置自定义路径到 PhantomJS 可执行文件,您需要确保可以在它被安装到 bin 文件夹中找到 phantomloader 文件。

如果您想要使用一个自定义 bin 文件夹,请参阅下文。

如果您想composer安装依赖所有可执行文件到自定义bin位置,在您的项目 composer.json 文件中设置的 bin 目录位置:
#composer.json
    {"config": {"bin-dir": "/path/to/your/projects/bin/dir"}}
您将需要确保该目录存在并且运行composer安装之前是通过composer可写。

一旦您已经更新了你的 bin路径,运行composer安装 PhantomJS:

#bash    $ php composer.phar install
这将为您的系统和所需的phantomloade文件正确安装PhantomJS可执行文件到你的composer.json 文件定义的bin路径。

现在你需要告诉客户端在哪里可以找到你的 bin 文件夹:
 
 
<?phpuse
 
JonnyW\PhantomJs\Client;
$client = Client::getInstance();
$client->setBinDir(‘/path/to/bin/dir‘);
从压缩文件安装

PHP PhantomJS 库包含几个依赖才能发挥作用,所以它建议你通过composer安装它,这将会为你处理你的依赖。如果您希望从 tar 文件的版本安装,那么您将需要手动安装这些依赖项。

PHP PhantomJS库目前需要以下依赖:
•    Symfony Config Component ~2.5
•    Symfony YAML Component ~2.5
•    Symfony Dependency Injection Component ~2.5
•    Symfony Filesystem Component ~2.5
•    Twig templating Component ~1.16
•    PhantomJS ~1.9
请确保组件的在你包括路径和 PhantomJS 可执行文件安装到您的项目的 bin 文件夹,如自定义安装部分所述。

用法
此页面包含如何使用 PHP PhantomJS 库的一些常见的例子。
•    基本要求
•    POST 请求
•    其他请求方法
•    响应数据
•    屏幕截图
•    设置视区大小
•    自定义超时
•    延迟页面渲染器
•    自定义运行选项
对于更高级的定制或加载自己的PhantomJS脚本,请参阅高级的文档。
基本要求
一个基本的 GET 请求:
<?php
    
    use JonnyW\PhantomJs\Client;
    
    $client = Client::getInstance();
    
    $request  = $client->getMessageFactory()->createRequest();
    $response = $client->getMessageFactory()->createResponse();
    
    $request->setMethod(‘GET‘);
    $request->setUrl(‘http://google.com‘);
    
    $client->send($request, $response);
    
    if($response->getStatus() === 200) {
        echo $response->getContent();
    }
您也可以通过消息工厂创建一个新的请求实例时设定的URL,请求方法和超时时间:
<?php
     
    use JonnyW\PhantomJs\Client;
    
    $client = Client::getInstance();
    
    $request  = $client->getMessageFactory()->createRequest(‘http://google.com‘, ‘GET‘, 5000);
    $response = $client->getMessageFactory()->createResponse();
        
    $client->send($request, $response);
    
    if($response->getStatus() === 200) {
        echo $response->getContent();
    }
POST 请求
一个基本的 POST 请求:
<?php
    
    use JonnyW\PhantomJs\Client;
    
    $client = Client::getInstance();
    
    $request  = $client->getMessageFactory()->createRequest();
    $response = $client->getMessageFactory()->createResponse();
    
    $data = array(
        ‘param1‘ => ‘Param 1‘,
        ‘param2‘ => ‘Param 2‘
    );
    
    $request->setMethod(‘POST‘);
    $request->setUrl(‘http://google.com‘);
    $request->setRequestData($data); // Set post data
    
    $client->send($request, $response);
其他请求方法

PHP PhantomJS 库支持下列请求方法:
•    OPTIONS
•    GET
•    HEAD
•    POST
•    PUT
•    DELETE
•    PATCH
请求方法可以通过消息工厂创建新请求实例时进行设置:
<?php
 
    use JonnyW\PhantomJs\Client;
    
    $client = Client::getInstance();
    
    $request  = $client->getMessageFactory()->createRequest(‘http://google.com‘, ‘PUT‘);
或在请求实例本身:
<?php
 
    use JonnyW\PhantomJs\Client;
    
    $client = Client::getInstance();
    
    $request  = $client->getMessageFactory()->createRequest();
    $request->setMethod(‘PATCH‘);
响应数据
通过访问下面的接口给予正确的响应:
访问方法    描述     返回类型
getHeaders() 返回所有响应标头的数组。Array
getHeader(header) 返回特定响应如内容类型标头的值。Mixed
getstatus () 响应状态代码例如 200。Int
getContent() 请求的页面的原始页面内容。String
getContentType() 请求的页面的内容类型。String
geturl () 所请求页面的 URL。String
getRedirectUrl() 如果响应是一个重定向,这将返回重定向 URL。String
isRedirect() 如果响应是一个重定向返回true,否则false。Boolean
getConsole() 返回的请求页面上的任何JavaScript错误的数组以及一个堆栈跟踪。Array

如果响应包含0状态码,则请求失败。检查请求的调试日志,以了解可能是什么出错了更详细的信息。
屏幕截图
你可以保存一个页面的屏幕截图到你的本地磁盘 ,通过创建屏幕截图捕捉请求并设置想要保存的文件的路径:

<?php
 
    use JonnyW\PhantomJs\Client;
    
    $client = Client::getInstance();
    
    $request  = $client->getMessageFactory()->createCaptureRequest(‘http://google.com‘);
    $response = $client->getMessageFactory()->createResponse();
    
    $file = ‘/path/to/save/your/screen/capture/file.jpg‘;
    
    $request->setCaptureFile($file);
    
    $client->send($request, $response);
您将需要确保你要保存到的文件的目录存在并且你的应用程序可写。
您还可以为屏幕捕获设置宽度、 高度、 x 和 y 轴:
<?php
 
    use JonnyW\PhantomJs\Client;
    
    $client = Client::getInstance();
    
    $request  = $client->getMessageFactory()->createCaptureRequest(‘http://google.com‘);
    $response = $client->getMessageFactory()->createResponse();
    
    $file = ‘/path/to/save/your/screen/capture/file.jpg‘;
    
    $top    = 10;
    $left   = 10;
    $width  = 200;
    $height = 400;
    
    $request->setCaptureFile($file);
    $request->setCaptureDimensions($width, $height, $top, $left);
    
    $client->send($request, $response);
设置视区大小

你可以轻松地为一个请求设置视口大小:

<?php
 
    use JonnyW\PhantomJs\Client;
    
    $client = Client::getInstance();
    
    $request  = $client->getMessageFactory()->createRequest(‘http://google.com‘);
    $response = $client->getMessageFactory()->createResponse();
        
    $width  = 200;
    $height = 400;
    
    $request->setViewportSize($width, $height);
    
    $client->send($request, $response);
自定义超时
默认情况下,每个请求将在 5 秒后超时。您可以 为每个请求设置自定义的超时时间 (以毫秒为单位):
<?php
 
    use JonnyW\PhantomJs\Client;
    
    $client = Client::getInstance();
    
    $request  = $client->getMessageFactory()->createRequest(‘http://google.com‘);
    $response = $client->getMessageFactory()->createResponse();
    
    $timeout = 10000; // 10 seconds
    
    $request->setTimeout($timeout);
    
    $client->send($request, $response);
延迟页面渲染器
有时屏幕捕获时,要等到页面完全加载才能保存捕获。在这种情况下,在这种情况下你可以设置一个页面呈现请求延迟 (以秒为单位):
<?php
 
    use JonnyW\PhantomJs\Client;
    
    $client = Client::getInstance();
    
    $request  = $client->getMessageFactory()->createCaptureRequest(‘http://google.com‘);
    $response = $client->getMessageFactory()->createResponse();
    
    $delay = 5; // 5 seconds
    
    $request->setDelay($delay);
    
    $client->send($request, $response);
您还可以为标准请求设置一个页面渲染延迟。
自定义运行选项
PhantomJS API包含了一系列的命令行选项,可以执行PhantomJS可执行文件时传递。这些也可以在一个请求之前通过客户端被传递。
<?php
 
    use JonnyW\PhantomJs\Client;
    
    $client = Client::getInstance();
    $client->addOption(‘--load-images=true‘);
    $client->addOption(‘--ignore-ssl-errors=true‘);
    
    $request  = $client->getMessageFactory()->createRequest(‘http://google.com‘);
    $response = $client->getMessageFactory()->createResponse();
 
    $client->send($request, $response);
你也可以设置一个包含多个 PhantomJS 选项的 JSON 配置文件路径:
<?php
 
    use JonnyW\PhantomJs\Client;
    
    $client = Client::getInstance();
    $client->addOption(‘--config=/path/to/config.json‘);
    
    $request  = $client->getMessageFactory()->createRequest(‘http://google.com‘);
    $response = $client->getMessageFactory()->createResponse();
 
    $client->send($request, $response);
见PhantomJS文档(http://phantomjs.org/api/command-line.html) 的命令行选项的完整列表。
高级用法
•    PhantomJS 命令行选项
•    自定义PhantomJS 脚本
o    编写自定义脚本
o    在您的脚本中使用自定义请求参数
o    加载您的脚本
PhantomJS 命令行选项
PhantomJS API 包含一系列执行可执行 PhantomJS 时可以传递的命令行选项。这些也可以在请求之前在客户端被传递 :

<?php
 
    use JonnyW\PhantomJs\Client;
    
    $client = Client::getInstance();
    $client->addOption(‘--load-images=true‘);
    $client->addOption(‘--ignore-ssl-errors=true‘);
    
    $request  = $client->getMessageFactory()->createRequest(‘http://google.com‘);
    $response = $client->getMessageFactory()->createResponse();
 
    $client->send($request, $response);
你也可以设置一个包含多个 PhantomJS 选项的 JSON 配置文件路径:

php
 
    use JonnyW\PhantomJs\Client;
    
    $client = Client::getInstance();
    $client->addOption(‘--config=/path/to/config.json‘);
    
    $request  = $client->getMessageFactory()->createRequest(‘http://google.com‘);
    $response = $client->getMessageFactory()->createResponse();
 
    $client->send($request, $response);
命令行选项的完整列表,请参见 PhantomJS 文档 http://phantomjs.org/api/command-line.html  。
自定义PhantomJS 脚本

在大多数情况下你不需要担心运行 PHP PhantomJS 库的 javascript 文件,但有时当你想要通过客户端执行您自己自定义的 PhantomJS 脚本。这可以通过使用内置的脚本装载器轻松实现。

脚本文件或 ‘程序‘ 提述他们在应用程序中紧密映射到请求。当您创建一个默认请求实例时,您基本上运行捆绑在与应用程序的默认 javascript 程序。当您创建一个捕获请求时,您正在运行的捕获过程。
<?php
 
    use JonnyW\PhantomJs\Client;
    
    $client->getMessageFactory()->createRequest(); // ~/Resources/procedures/default.proc
    $client->getMessageFactory()->createCaptureRequest(); // ~/Resources/procedures/capture.proc

编写自定义脚本

创建脚本的第一步是在某处创建一个过程文件。本指南为我们将它称为 my_procedure.proc,但实际上它可以被叫做任何你喜欢的。唯一的要求是文件扩展名必须是.proc.。
在某处创建文件,并确保它可以通过你的应用程序读取。记下您创建的文件的目录路径,当加载在本指南稍后解释的你的脚本你将需要。
#bash
    
    $ touch my_procedure.proc
    $ chmod 755 my_procedure.proc
下一步在您的文本编辑器中打开您的程序文件和写您的 PhantomJS 脚本。PhantomJS 文档在编写自定义脚本有更详细资料。
// my_procedure.proc
 
    var page  = require(‘webpage‘).create();
    
    page.open (‘{{ request.getUrl() }}‘, ‘{{ request.getMethod() }}‘, ‘{{ request.getBody() }}‘, function (status) {
         
        // It is important that you exit PhantomJS
        // when your script has run or when you
        // encounter an error
        phantom.exit(1);
    });
    
    ...
重要
请确保该 phantom.exit(1);总是被称为运行您的脚本后,或如果您遇到一个错误。这需要你处理PhantomJS错误时,以确保你退出的 PhantomJS 脚本,脚本成功执行与否。如果你不叫 phantom.exit(1);然后 PhantomJS 将继续运行,直到您的 PHP 脚本超时。如果你发现你自定义的脚本挂,最有有可能是这个原因。
它是一个好的习惯,在您退出 PhantomJS 的脚本中创建全局错误处理程序:
// my_procedure.proc
 
    phantom.onError = function(msg, trace) {
 
        phantom.exit(1);
    };
    
    ...
未完待续。。
翻译很烂,请见谅,原文见http://jonnnnyw.github.io/php-phantomjs/

PHP PhantomJs中文文档(翻译)

标签:

原文地址:http://www.cnblogs.com/luoyunshu/p/4714018.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!