Laravel 配合 puppeteer 抓取 SPA 页面 
                                                    
                        
                    
                    
  
                    
                    由于 Vue,React等 js 框架的广泛使用,传统的 php 爬虫对于 SPA 的页面,只能爬到这样一个 html 文件,没有任何用,因为页面完全是靠 js 在前端渲染出来的
但是现在我们可以用 php 配合 puppeteer 抓取 js 渲染之后的页面
- 先创建一个 Laravel 项目 
composer create-project laravel/laravel crawler - 安装依赖 
composer require nesk/puphpeteer和npm install @nesk/puphpeteer(可以把 Laravel 默认的 npm 依赖全部删了) - 新建命令 
php artisan make:command ShallowScrapingData --command=crawler:shallow-scraping再在app\Console\Commands下新建ScrapingHelper.php - 编辑 
ShallowScrapingData.php
编辑... use ScrapingHelper; ... public function handle(){ $this->info($this->scrape('https://www.iviewui.com')); } ...ScrapingHelper.php<?php namespace App\Console\Commands; use Nesk\Puphpeteer\Puppeteer; trait ScrapingHelper{ public function scrape(String $url){ $puppeteer = new Puppeteer; // 新建 Puppeteer 实例 $browser = $puppeteer->launch(); // 启动无头浏览器 $page = $browser->newPage(); // 打开新的标签页 try{ $page->tryCatch->goto($url,[ 'timeout' => 0, 'read_timeout' => 0 ]); // 访问页面 $html = $page->content(); $browser->close(); return $html; // 返回 js 渲染后的页面 }catch(Exception $error){ ... } } ... } - 执行 
php artisan crawler:shallow-scraping,效果如下
可以看到红框处即是Vue的渲染标志 
可能遇到的问题
libX11-xcb.so.1: cannot open shared object file: No such file or directory
解决办法:apt-get install gconf-service libxext6 libxfixes3 libxi6 libxrandr2 libxrender1 libcairo2 libcups2 libdbus-1-3 libexpat1 libfontconfig1 libgcc1 libgconf-2-4 libgdk-pixbuf2.0-0 libglib2.0-0 libgtk-3-0 libnspr4 libpango-1.0-0 libpangocairo-1.0-0 libstdc++6 libx11-6 libx11-xcb1 libxcb1 libxcomposite1 libxcursor1 libxdamage1 libxss1 libxtst6 libappindicator1 libnss3 libasound2 libatk1.0-0 libc6 ca-certificates fonts-liberation lsb-release xdg-utils wget--no-sandbox is not supported
解决办法:不要用 root 用户执行php artisan crawler:shallow-scraping
本作品采用《CC 协议》,转载必须注明作者和本文链接
          
                    
                    
          
          
                关于 LearnKu
              
                    
                    
                    
 
推荐文章: