使用 selenium 实现 react/vue 的 SSR 服务端渲染

平凡
2018-07-12 17:14:54
490 阅读

最近打算做下网站seo,于是就研究了下服务端渲染(SSR)。

前几天看了一篇文章《使用 PHP 来做 Vue.js 的 SSR 服务端渲染》,然后就试着按照文章的教程去实现,折腾了一会发现好像不太管用,很多浏览器特定的代码都不能用,最后决定放弃。

后面想到另一种解决思路,就是利用 selenium 来渲染页面内容。

Selenium 是一个用于Web应用程序测试的工具。Selenium测试直接运行在浏览器中,就像真正的用户在操作一样。支持的浏览器包括IE(7, 8, 9, 10, 11),Mozilla Firefox,Safari,Google Chrome,Opera等。这个工具的主要功能包括:测试与浏览器的兼容性——测试你的应用程序看是否能够很好得工作在不同浏览器和操作系统之上。测试系统功能——创建回归测试检验软件功能和用户需求。支持自动录制动作和自动生成 .Net、Java、Perl等不同语言的测试脚本。

  1. 首先我们先安装一款浏览器,这里我选择用chrome
    在 /etc/yum.repos.d/ 目录下新建文件 google-chrome.repo, 并且在该文件中添加如下内容:

    [google-chrome]
    name=google-chrome
    baseurl=http://dl.google.com/linux/chrome/rpm/stable/x86_64
    enabled=1
    gpgcheck=1
    gpgkey=https://dl.google.com/linux/linux_signing_key.pub
    

    安装google chrome浏览器

    yum -y install google-chrome-stable
    

    PS: Google官方源可能在中国无法使用,导致安装失败或者在国内无法更新,可以添加以下参数来安装:

    yum -y install google-chrome-stable --nogpgcheck
    

    查看版本

    google-chrome-stable -version 
    
  2. 代码实现
    安装 yanthink/selenium

    composer require yanthink/selenium="@dev"
    

    安装好后,我们在 routes/web.php 文件下添加一条路由:

    Route::domain('spider.einsition.com')->group(function () {
    	Route::get('/{uri?}', 'SpiderController@render')->where('uri',  '(.*)');
    });
    

    然后新建一个 SpiderController.php 文件,用来实现渲染页面内容

    <?php
    
    namespace App\Http\Controllers;
    
    use Illuminate\Http\Request;
    use Yanthink\Selenium\Browser;
    use Yanthink\Selenium\Selenium;
    
    Selenium::useChromeDriver();
    Selenium::disableAutoStartChromeDriver();
    
    class SpiderController extends Controller
    {
    	public function render(Request $request, Selenium $selenium)
    	{
    		$selenium->browse(function (Browser $browser) use ($request) {
    			$url = 'https://www.einsition.com' . $request->getRequestUri(); // 需要渲染的页面
    			echo $browser->visit($url)->waitFor('#layout')->driver->getPageSource();
    			exit;
    		});
    	}
    }
    
  3. 启动 chromedriver

    nohup ./vendor/yanthink/selenium/bin/chromedriver-linux --port=9515 2>&1 &
    
  4. nginx配置,将搜索引擎的请求反代到渲染路由上

    location / {
    	if ($http_user_agent ~* "Baiduspider|360Spider|bingbot|Googlebot|Sogou web spider") {
    		proxy_pass http://spider.einsition.com;
    	}
    	try_files $uri $uri/ /index.html?$query_string;
    }
    

    重启nginx

    systemctl reload nginx.service
    
  5. 用curl测试下效果

    curl --header 'User-Agent: Baiduspider+(+http://www.baidu.com/search/spider.htm)' 'https://www.einsition.com/article/list'
    

    file

OK,搞定了!

1 评论
  • comment-avatar

    🐼🐼🐼

    • 回复