出于某种原因,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/