PhantomJS 基本用法
使用phantomjs發起一個請求非常簡單:
[PHP] 純文本查看 複制代碼
<?php
use JonnyW\PhantomJs\Client;
$client = Client::getInstance();
/**
* @see JonnyW\PhantomJs\Http\Request
**/
$request = $client->getMessageFactory()->createRequest('http://phpreturn.com', 'GET');
/**
* @see JonnyW\PhantomJs\Http\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] 純文本查看 複制代碼 <?php
use JonnyW\PhantomJs\Client;
$client = Client::getInstance();
$width = 800;
$height = 600;
$top = 0;
$left = 0;
/**
* @see JonnyW\PhantomJs\Http\CaptureRequest
**/
$request = $client->getMessageFactory()->createCaptureRequest('http://phpreturn.com', 'GET');
$request->setOutputFile('/path/to/save/capture/file.jpg');
$request->setViewportSize($width, $height);
$request->setCaptureDimensions($width, $height, $top, $left);
/**
* @see JonnyW\PhantomJs\Http\Response
**/
$response = $client->getMessageFactory()->createResponse();
// Send the request
$client->send($request, $response);
將頁面導出為PDF:
[PHP] 純文本查看 複制代碼 <?php
use JonnyW\PhantomJs\Client;
$client = Client::getInstance();
/**
* @see JonnyW\PhantomJs\Http\PdfRequest
**/
$request = $client->getMessageFactory()->createPdfRequest('http://phpreturn.com', 'GET');
$request->setOutputFile('/path/to/save/pdf/document.pdf');
$request->setFormat('A4');
$request->setOrientation('landscape');
$request->setMargin('1cm');
/**
* @see JonnyW\PhantomJs\Http\Response
**/
$response = $client->getMessageFactory()->createResponse();
// Send the request
$client->send($request, $response);
自定義一個超時時間:
預設情況下每個請求超時時間為5秒,我們可以自定義一個超時時間.
[PHP] 純文本查看 複制代碼 <?php
...
$timeout = 10000; // 10 秒
$request = $client->getMessageFactory()->createRequest('http://phpreturn.com');
$request->setTimeout($timeout);
...
|