我想测试 anchor 标记上的单击事件是否会触发正确的 DOM 转换。我在浏览器中看到的内容有效,并且我几乎检查了代码的每一行都返回了我想要的内容,除了当我让 PhantomJS 执行此操作时,预期的 DOM 转换似乎没有触发。
这是我的代码:
page.open(url, function(status) {
if (status === "success") {
var specifications = page.evaluate(function() {
var a = document.querySelector("a[href='#Specifications']");
var e = document.createEvent('MouseEvents');
e.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
a.dispatchEvent(e);
return document.querySelector("div#Specifications").innerHTML;
});
console.log(specifications);
phantom.exit()
} else {
phantom.exit(1);
});
});
我最初只是调用 document.querySelector("a[href='#Specifications']").click();
得到相同的结果。在我的 Web 浏览器中,单击该链接会触发 DOM 转换。然而我无法在 PhantomJS 中重现它。
最佳答案
经过长时间弄清楚发生了什么,这里为遇到类似问题的人提供了一些建议。
首先,确保您的选择器没有问题。就我而言,我决定坚持使用文档 API。与某些人所说的发送点击事件不同,以下方法可以正常工作:
document.querySelector("a[href='#some_section']").click();
您也应该能够将 jQuery 与 page.includeJs()
结合使用。
确保在调用 click()
后使用 onResourceRequested
和 onResourceReceived
请求并接收页面资源,如下所示:
page.onResourceRequested = function(data, request) {
console.log("phantomJS: resource requested: " + data.url);
};
page.onResourceReceived = function(response) {
console.log("phantomJS: resource received: " + response.url);
};
最后,请确保您是否正在评估需要在单击事件后插入的某些值,该操作是在收到资源后完成的。我最终做的是:
setTimeout(function() {
var data = page.evaluate(function() {
return document.querySelector('div#InsertDiv').innerHTML;
});
console.log(data);
phantom.exit();
}, 2000);
基本上,如果正在请求外部资源,您必须为其设置异步等待时间。
关于javascript - PhantomJS - 从点击事件加载的内容不会加载到 DOM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35914882/