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
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();
?>