2015-08-27 65 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()代码没有获得外界定义的变量,所以值必须在明确的被传递。