phantomjs 抓取頁面失敗
阿新 • • 發佈:2018-11-05
蛛蛛爬蟲無法抓取 angularjs 渲染的頁面,解決這個問題通常要用到第三方技術,phantomjs 是個不錯的選擇,今天測試抓取 www.baidu.com 沒有問題(phantomjs getpage.js "http://www.baidu.com"),但抓取自己的網站卻有問題 (phantomjs getpage.js "http://www.port56.com"),經過分析,發現是因為我的網站做了跳轉,在 github 上找到解決方案,完整程式碼如下
var myurl = 'http://www.port56.com'; var page = require('webpage').create(); var system = require('system'); var url = system.args[1]; page.viewportSize = { width: 1280, height: 1014 }; var renderPage = function (url) { page = require('webpage').create(); page.onNavigationRequested = function(url, type, willNavigate, main) { if (main && url!=myurl) { myurl = url; page.close(); setTimeout('renderPage(myurl)',1000); //Note the setTimeout here } }; page.open(url, function(status) { if (status==="success") { // 頁面渲染需要時間,延遲2秒取渲染的頁面內容 setTimeout(function(){ console.log(page.content); //page.render('yourscreenshot.png'); phantom.exit(0); } , 2000) } else { console.log("failed") phantom.exit(1); } }); } renderPage(myurl);