PHP抓取網頁執行JS phantomjs
阿新 • • 發佈:2018-12-14
PHP抓取網頁,網頁內容是通過JS載入的,這時需要執行JS來載入內容。
需要用到phantomjs。下面是windows的安裝方法。
1.安裝phantomjs
下載完成解壓到E:\software\phantomjs-2.1.1-windows
把E:\software\phantomjs-2.1.1-windows\bin新增到環境變數:
右鍵我的電腦-》屬性-》高階系統設定-》環境變數-》在系統變數找到Path編輯:在最後新增 ;E:\software\phantomjs-2.1.1-windows\bin
安裝完成
2.PHP phantomjs安裝
需要使用composer來安裝,在專案的composer.json加上:
{
"require": {
"jonnyw/php-phantomjs":"4.*"
}
}
然後開啟命令列進入到專案路徑,執行:
composer update
安裝完成。
3.PHP執行JS
<?php require 'vendor/autoload.php'; use JonnyW\PhantomJs\Client; $client = Client::getInstance(); $client->getEngine()->setPath('E:/software/phantomjs-2.1.1-windows/bin/phantomjs.exe'); //設定phantomjs位置 $client->getEngine()->addOption('--load-images=false'); $client->getEngine()->addOption('--ignore-ssl-errors=true'); $url = 'https://www.baidu.com'; $request = $client->getMessageFactory()->createRequest($url, 'GET'); $timeout = 10000; //設定超時 $request->setTimeout($timeout); $request->addSetting('userAgent', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36');//設定ua $response = $client->getMessageFactory()->createResponse(); $client->send($request, $response); echo $response->getContent(); ?>