2013-10-25 58 views
4

到iframe中,我想使用純phantom.js代碼開關與phantom.js

這裏切換到一個iframe是我第一次嘗試

var page = new WebPage(); 
var url = 'http://www.theurltofectch' 
page.open(url, function (status) { 
    if ('success' !== status) { 
     console.log("Error"); 
    } else { 
     page.switchToFrame("thenameoftheiframe"); 
     console.log(page.content); 
     phantom.exit(); 
    } 
}); 

它產生唯一的主網頁的源代碼。任何想法 ?

請注意,iframe域與主頁面域不同。

+1

1.你嘗試調用'page.render ()'在切換之前和切換後看看產生了什麼圖像? 2.你確信''nameofhififrame'實際上出現在加載的URL中嗎? –

回答

1

請給這個嘗試我相信它可能是一個異步問題,這意味着iframe在嘗試訪問它時不存在。我從另一篇文章中收到了以下代碼片段。

var page = require('webpage').create(), 
    testindex = 0, 
    loadInProgress = false; 

page.onConsoleMessage = function(msg) { 
    console.log(msg); 
}; 

page.onLoadStarted = function() { 
    loadInProgress = true; 
    console.log("load started"); 
}; 

page.onLoadFinished = function() { 
    loadInProgress = false; 
    console.log("load finished"); 
}; 

/* 
page.onNavigationRequested = function(url, type, willNavigate, main) { 
    console.log('Trying to navigate to: ' + url); 
    console.log('Caused by: ' + type); 
    console.log('Will actually navigate: ' + willNavigate); 
    console.log('Sent from the page\'s main frame: ' + main); 
}; 
*/ 


/* 
    The steps array represents a finite set of steps in order to perform the unit test 
*/ 

var steps = [ 
    function() { 
    //Load Login Page 
    page.open("https://www.yourpage.com"); 
    }, 
    function() { 
    //access your iframe here 
    page.evaluate(function() { 


    }); 
    }, 
    function() { 
    //any other step you want 
    page.evaluate(function() { 



    }); 
    }, 
    function() { 
    // Output content of page to stdout after form has been submitted 
    page.evaluate(function() { 
     //console.log(document.querySelectorAll('html')[0].outerHTML); 
    }); 

    //render a test image to see if login passed 
    page.render('test.png'); 

    } 
]; 


interval = setInterval(function() { 
    if (!loadInProgress && typeof steps[testindex] === "function") { 
    console.log("step " + (testindex + 1)); 
    steps[testindex](); 
    testindex++; 
    } 
    if (typeof steps[testindex] !== "function") { 
    console.log("test complete!"); 
    phantom.exit(); 
    } 
}, 50); 
2

取代

console.log(page.content); 

console.log(page.frameContent); 

應該返回幀phantomjs的內容切換到。

如果iframe是從另一個域您可能需要添加--web安全= no選項是這樣的:

phantomjs --web-security=no myscript.js 

作爲一個額外的信息,什麼xMythicx說可能是真實的。頁面完成加載後,一些iframe通過Javascript呈現。如果iframe內容爲空,那麼在開始從頁面抓取內容之前,您需要等待所有資源完成加載。但這是另一個問題,如果你需要一個答案,我建議你問一個關於它的新問題,我會在那裏回答。

1

已經爲I幀同樣的問題,

phantomjs --web安全=無

幫助我的情況:]