2014-01-06 87 views
2

我試圖使一些內嵌HTML使用以下PhantomJs腳本鏈接到外部CSS文件:PhantomJs:內嵌HTML與外部CSS文件

var page = require('webpage').create(); 
page.content = ''; 
page.content += '<html><head>'; 
page.content += '<link rel="stylesheet" href="http://example.com/css/layout.css" type="text/css" media="Screen">'; 
page.content += '</head><body>'; 
page.content += '<h1>test</h1>'; 
page.content += '</body></html>'; 

page.onResourceRequested = function(requestData, request) { 
    console.log('::loading', requestData['url']); // this doesn't get logged 
}; 

page.onLoadFinished = function() { 
    console.log('::rendering'); 
    page.render('output.png'); 
    phantom.exit(); 
}; 

layout.css可以訪問文件還好有wget

但這裏的phantomjs的輸出:

$ ./phantomjs --debug=true render_demo.js 
... snip ... 
2014-01-06T12:17:53 [DEBUG] WebPage - updateLoadingProgress: 10 
2014-01-06T12:17:53 [DEBUG] WebPage - updateLoadingProgress: 10 
2014-01-06T12:17:53 [DEBUG] WebPage - updateLoadingProgress: 100 
2014-01-06T12:17:53 [DEBUG] Network - Resource request error: 5 ("Operation canceled") URL: "http://example.com/css/layout.css" 
::rendering 

沒有創建輸出.png文件。

有關如何確保外部CSS資源在呈現前完全加載的任何想法? 它似乎工作好,當我請求與page.open

回答

6

如前所述benweet,你需要設置page.content只有一次,因爲它會在每次觸發重新加載。

因此,除此之外,您還需要在之前定義您的回調實際設置頁面內容。

嘗試像這樣代替:

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

page.onResourceRequested = function(requestData, request) { 
    console.log('::loading', requestData['url']); // this does get logged now 
}; 

page.onLoadFinished = function() { 
    console.log('::rendering'); 
    page.render('output.png'); 
    phantom.exit(); 
}; 

var content = ''; 
content += '<html><head>'; 
content += '<link rel="stylesheet" href="http://example.com/css/layout.css" type="text/css" media="screen">'; 
content += '</head><body>'; 
content += '<h1>test</h1>'; 
content += '</body></html>'; 
page.content = content; 
+0

就是這樣,謝謝! 我犯了一個錯誤,認爲函數分配總是先在一個範圍內執行(與函數定義相同)。 – EoghanM

2

相同的HTML您有一個名爲localToRemoteUrlAccessEnabled控制,如果本地的頁面可以訪問遠程ressources設置。它似乎默認爲false,所以你應該嘗試改變它。

PhantomJS設置都記錄here,所以更改此設置想在你的代碼來完成:

page.settings.localToRemoteUrlAccessEnabled = true; 

剛過創建頁面。由於您的頁面內容是通過腳本生成的,因此我不知道它是否真的被認爲是本地或遠程的。如果此設置不起作用,您可以嘗試將webSecurityEnabled設置爲false

+0

嗯,似乎並沒有工作。從鏈接到它的文檔說,「注意:這些設置僅在首次調用page.open函數期間適用」,並且我沒有page.open調用。 – EoghanM

+0

同上'webSecurityEnabled' – EoghanM

+0

@EoghanM:很抱歉聽到這句話,無法幫助你,祝你好運! – Antoine

0

您必須設置page.content一次。多次調用setter會多次加載頁面,並取消以前未完成的異步資源加載。

var page = require('webpage').create(); 
var content = ''; 
content += '<html><head>'; 
content += '<link rel="stylesheet" href="http://example.com/css/layout.css" type="text/css" media="Screen">'; 
content += '</head><body>'; 
content += '<h1>test</h1>'; 
content += '</body></html>'; 
page.content = content; 
+0

謝謝,我已經探討了這種調整,但它沒有任何區別:我仍然在調試輸出中得到'取消操作'消息。 – EoghanM