PhantomJS / SlimerJS无法通过document.querySelector()查找元素

时间:2015-08-27 15:47:05

标签: javascript phantomjs slimerjs

由于某种原因,querySelector和class逐个元素在存在的元素上返回null。

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>

在slimerjs中运行返回&#34; document.querySelector(...)为null&#34;

1 个答案:

答案 0 :(得分: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()内的代码无法访问外部定义的变量,因此必须显式传入值。