PhantomJS - 从单击事件加载的内容不会加载到 DOM

PhantomJS - content loaded from click event does not load to DOM

本文关键字:加载 DOM 单击 事件 PhantomJS      更新时间:2023-09-26

我想测试锚标签上的点击事件触发正确的 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()一起使用。

确保在使用如下所示的onResourceRequestedonResourceReceived调用click()后请求和接收页面资源:

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);

基本上,如果正在请求外部资源,则必须为其设置异步等待时间。