javascript - PhantomJS/SlimerJS 无法通过 document.querySelector() 找到元素

标签 javascript phantomjs slimerjs

出于某种原因,querySelector 和 get element by 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 中运行返回“document.querySelector(...) is null”

最佳答案

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

关于javascript - PhantomJS/SlimerJS 无法通过 document.querySelector() 找到元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32254021/

相关文章:

javascript - casperjs无限循环超时不等待

javascript - 当元素从动态创建的页面加载到文档中时运行函数

javascript - 使用 clipRect() 后设置 PhantomJS 捕获整个屏幕

ember.js - PhantomJS 2.0 卡在 ember 测试上

javascript - CasperJS : dropdown list; select an option, 代码在浏览器和 slimer 中有效,但在 phantom 中无效

ssl - HTTPS 站点上的 PhantomJS "SSL handshake failed",即使使用所有标志

javascript - 为非多任务运行 this.files

javascript - Chrome 没有选择源 map ,尽管它已启用

javascript - 检查谓词(第二个参数)在集合的所有元素(第一个参数)上是否为真

javascript - PhantomJS queryselector().textcontent 不返回任何内容