2017-01-03 53 views
0

我试图获取某些url的屏幕截图并使用phantomjs将其显示在chrome浏览器中。我怎么做?任何帮助将不胜感激,但没有任何显示在网页上。 这就是我的代码的外观。使用phantomjs获取chrome浏览器中的url的屏幕截图

<!DOCTYPE html> 
<html> 
    <head> 
     <title>WSST</title> 
     <script type="text/javascript"/> 
     var URLS = ["https://google.com", 
      "http://www.bing.com/", 
      "https://www.yahoo.com/", 
      "https://www.npmjs.com/package/phantomjs-html", 
      "" 
      ] 

var SCREENSHOT_WIDTH = 1280; 
var SCREENSHOT_HEIGHT = 900; 
var LOAD_WAIT_TIME = 5000; 

var getPageTitle = function(page){ 
    var documentTitle = page.evaluate(function(){ 
     return document.title; 
    }) 
    console.log("getting title:", documentTitle) 
    return documentTitle; 
} 

var getPageHeight = function(page){ 
    var documentHeight = page.evaluate(function() { 
     return document.body.offsetHeight; 
    }) 
    console.log("getting height:", documentHeight) 
    return documentHeight; 
} 

var renderPage = function(page){ 

    var title = getPageTitle(page); 

    var pageHeight = getPageHeight(page); 

    page.clipRect = { 
     top:0,left:0,width: SCREENSHOT_WIDTH, 
     height: pageHeight 
    }; 
    page.render("d:/screenshots/"+title+".png"); 
    console.log("rendered:", title+".png") 
} 

var exitIfLast = function(index,array){ 
    console.log(array.length - index-1, "more screenshots to go!") 
    console.log("~~~~~~~~~~~~~~") 
    if (index == array.length-1){ 
     console.log("exiting phantomjs") 
     phantom.exit(); 
    } 
} 

var takeScreenshot = function(element){ 

    console.log("opening URL:", element) 

    var page = require("webpage").create(); 

    page.viewportSize = {width:SCREENSHOT_WIDTH, height:SCREENSHOT_HEIGHT}; 

    page.open(element); 

    console.log("waiting for page to load...") 

    page.onLoadFinished = function() { 
     setTimeout(function(){ 
      console.log("that's long enough") 
      renderPage(page) 
      exitIfLast(index,URLS) 
      index++; 
      takeScreenshot(URLS[index]); 
     },LOAD_WAIT_TIME) 
    } 

} 

var index = 0; 

takeScreenshot(URLS[index]); 
     </script> 
    </head> 
    <body style = "background-color: #FFFFFF"> 
     <span class = "hey">Page Start</span> 
     <br><br><br><br><br><br><br><br><br><br><br><br><br><br> 
     <br><br><br><br><br><br><br><br><br><br><br><br><br><br> 
     <br><br><br><br><br><br><br><br><br><br><br><br><br><br> 

    Page End 
    </body> 
</html> 

回答

2

您无法使用浏览器端JavaScript运行PhantomJS。

为了做到这一点,你需要在你的网络服务器上运行PhantomJS(使用你链接的任何服务器端语言,Phantom已经绑定了很多,包括通过Node.JS的JavaScript)。

你的客户端代码,然后可以将图像元素进入页面:

var page_to_show = URLS[index]; 
var image_url = "http://example.com/myPhantomWrapper?page=" + encodeURIComponent(page_to_show); 
var image = document.createElement("img"); 
image.src = image_url; 
document.body.appendChild(image); 

你的服务器端代码,然后可以从查询字符串的URL,并使用PhantomJS生成图像,然后返回图像在HTTP响应中。

+0

@Vikas - 步骤1:选择一种编程语言。第2步:学习使用该语言进行服务器端编程。步骤3:找到它的PhantomJS绑定。第4步:阅读这些绑定的文档 – Quentin

相关问题