2015-08-27 109 views
0

由於某些原因,querySelector和get元素按類在元素上返回null。PhantomJS/SlimerJS通過document.querySelector()找不到元素

PhantomJS/SlimerJS

page.open('file:///Users/yeahsame/Desktop/index.html', function(status) 
{ 
    console.log("Starting execution"); 
    document.querySelector("input")[0].value = "not working whatsoever"; 

    phantom.exit(); 
}); 

HTML:在slimerjs回報

<!doctype html> 
<body> 
    <input class="form-control email input-lg"></input> 
    <button class="btn" onclick="location.href='notexist.html'">submit</button> 
</body> 

運行 「document.querySelector(...)爲空」

回答

1

PhantomJS/SlimerJS有兩個背景。內頁(DOM)上下文只能通過沙盒page.evaluate()函數訪問。其外部存在一個document對象,但它無法訪問頁面DOM。

page.open('file:///Users/yeahsame/Desktop/index.html', function(status) 
{ 
    console.log("Starting execution"); 
    page.evaluate(function(selector, value){ 
     document.querySelector(selector)[0].value = value; 
    }, "input", "not working whatsoever"); 

    page.render("screenshot.png"); 
    phantom.exit(); 
}); 

page.evaluate()代碼沒有獲得外界定義的變量,所以值必須在明確的被傳遞。