2015-08-27 1 views
0

По какой-то причине querySelector и get element by class возвращают 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:

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

Run в slimerjs возвращается "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() не имеет доступа к переменным, определенным снаружи, так что значения должны быть явно прошли в.