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
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM