PHP获取HTML内容及动态渲染js加载内容

  写爬虫的时候,使用guzzle异步并发的get请求真的好用,可以快速爬取,及时PHP不是多线程的,却能使用协程实现异步并发-用户态的多线程,也有时候,请求地址返回的页面很多待执行的JavaScript代码,数据需要动态渲染上去,这里有个简单的方法

就是使用querylist,用了这个扩展也可以不再依赖php的dom解析工具-simpledom,也自带了远程获取功能。

1.安装

安装querylist

composer require jaeger/querylist

安装phantomjs

composer require jaeger/querylist-phantomjs  //PHP版本必须 >=7.0

下载对应你电脑系统的PhantomJS二进制文件,放到电脑任意路径,下面会用到这个路径,下载页面直达:http://phantomjs.org/download.html

2.使用

Linux下示例:

use QL\QueryList;
use QL\Ext\PhantomJs;
$ql = QueryList::getInstance();
// 安装时需要设置PhantomJS二进制文件路径
$ql->use(PhantomJs::class,'/usr/local/bin/phantomjs');
//or Custom function name
$ql->use(PhantomJs::class,'/usr/local/bin/phantomjs','browser');

Windows下示例:

$ql->use(PhantomJs::class,'C:/phantomjs/bin/phantomjs.exe');
$html = $ql->browser('https://m.toutiao.com')->getHtml();
print_r($html);

相关文档:

https://doc.querylist.cc/

示例:

检索书籍在百度的搜索排行榜,直接curl发送get请求获取到的html是木有数据的,因为搜索结果页是异步JavaScript获取的。

<?php

// 设置脚本超时
set_time_limit(0);
// 内存限制
ini_set('memory_limit', '2014M');
// 第三方库
require_once('./vendor/autoload.php');
use QL\QueryList;
use QL\Ext\PhantomJs;
// 获取搜索结果
$book_name = '我的贴身校花';
$ql = QueryList::getInstance();
$ql->use(PhantomJs::class,'D:\webserver\www\phantomjs.exe');
$html = $ql->browser('https://m.baidu.com/s?word='.urlencode($book_name))->getHtml();
$z = $ql->find('.c-result-content:eq(0)')->find('.c-color-gray:eq(0)')->texts();
$z = $z->all();
file_put_contents('./check.log', $v.' ==> '.current($z)."\n", FILE_APPEND);

搜索截图:

---------------------
作者:qq_42413925
来源:CSDN
原文:https://blog.csdn.net/qq_42413925/article/details/80619697
版权声明:本文为博主原创文章,转载请附上博文链接!

posted @ 2018-10-22 11:22  许伟强  阅读(10034)  评论(0编辑  收藏  举报