-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathPhantomJs.php
76 lines (66 loc) · 2.29 KB
/
PhantomJs.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<?php
/**
* Created by PhpStorm.
* User: Jaeger <[email protected]>
* Date: 2017/9/30
* Use PhantomJS to crawl Javascript dynamically rendered pages.
*/
namespace QL\Ext;
use JonnyW\PhantomJs\Http\RequestInterface;
use QL\Contracts\PluginContract;
use QL\QueryList;
use JonnyW\PhantomJs\Client;
use Closure;
class PhantomJs implements PluginContract
{
protected static $browser = null;
public static function install(QueryList $queryList, ...$opt)
{
// PhantomJS bin path
$phantomJsBin = $opt[0];
$name = $opt[1] ?? 'browser';
$queryList->bind($name,function ($request,$debug = false,$commandOpt = []) use($phantomJsBin){
return PhantomJs::render($this,$phantomJsBin,$request,$debug,$commandOpt);
});
}
public static function render(QueryList $queryList,$phantomJsBin,$url,$debug = false,$commandOpt = [])
{
$client = self::getBrowser($phantomJsBin,$commandOpt);
$request = $client->getMessageFactory()->createRequest();
if($url instanceof Closure){
$request = $url($request);
}else{
$request->setMethod('GET');
$request->setUrl($url);
}
$response = $client->getMessageFactory()->createResponse();
if($debug) {
$client->getEngine()->debug(true);
}
$client->send($request, $response);
if($debug){
print_r($client->getLog());
print_r($response->getConsole());
}
$html = '<html>'.$response->getContent().'</html>';
$queryList->setHtml($html);
return $queryList;
}
protected static function getBrowser($phantomJsBin,$commandOpt = [])
{
$defaultOpt = [
'--load-images' => 'false',
'--ignore-ssl-errors' => 'true'
];
$commandOpt = array_merge($defaultOpt,$commandOpt);
if(self::$browser == null){
self::$browser = Client::getInstance();
self::$browser->getEngine()->setPath($phantomJsBin);
}
foreach ($commandOpt as $k => $v) {
$str = sprintf('%s=%s',$k,$v);
self::$browser->getEngine()->addOption($str);
}
return self::$browser;
}
}