【问题标题】:Why the statement inside setInterval function is not getting executed in Phantomjs?为什么 setInterval 函数中的语句没有在 Phantomjs 中执行?
【发布时间】:2017-10-20 18:21:16
【问题描述】:

我正在尝试使用 Phantomjs 登录网站。当我在填写表单元素后单击 loginButton 时,我试图在 setInterval 函数中找到一些元素 id,因为我希望页面首先加载(给 2 秒),然后只搜索元素,但这里的问题是:我的 setInterval 中的语句没有被执行。这是 phantomjs 代码:

var url = "http://www.someUrl.com";
var page = require('webpage').create();

page.onConsoleMessage = function(msg, lineNo, sourceId){
    console.log('console: ' + msg);
};

page.onLoadFinished = function(status){
    console.log("Loading finished");
    page.render('webpage.png');
};

page.open(url, function(status){
    page.evaluate(function(){
        arr = document.getElementsByClassName('formLabel');
        if (typeof arr !== 'undefined'){
            arr[0].value = 'Login-id';
            arr[1].value = 'Password';
        }
        document.getElementById('loginButton').click();
        setInterval(function(){
            console.log("Downloading the file");
            document.getElementById('downloadButton').click();
        }, 2000);
    });
});

当我执行上面的代码时,我得到的输出是:-

Loading finished
Loading finished

出于调试目的,我在 setInterval 函数中写入了console.log('Downloading the file'),但该语句没有被执行。 我还将网页呈现为图像page.render('webpage.png') 以检查我是否能够成功登录。我看到登录成功。所以,我在这里有几个问题:-

  1. 为什么setInterval 函数中的那些语句没有被执行?
  2. 我应该在哪里编写这些语句才能使其正常工作?

事实上,当我在loginButton.click() 语句之后编写这些语句时,我得到了这个错误 - TypeError: 'null' is not an object (near 'downloadButton').click();... '),这意味着页面没有加载到那个时候。因此,我将它们写在 setInterval 函数中,并将等待时间设置为 2 秒。

PS : 我的click 语句没有问题,因为我的loginButton.click 正在工作。

提前致谢。

【问题讨论】:

  • 注册到 page.onError 事件。 element.click 可能未定义。
  • @Artjom B. 在那种情况下我会得到错误 - 未定义的元素。但我没有收到任何错误,而且语句 console.log('Downloading the file') 没有执行。这表明它没有进入 setInterval 函数内部。
  • 在这种情况下,当注释掉点击并将typeof arr !== 'undefined' 更改为arr.length > 0 时,我无法使用 PhantomJS 1.9.8 或 v2.0.0 重现您的问题。 arr 已定义,它始终是一个 NodeList,但它可能为空。
  • 查看有关在 Phantom 中使用 click 方法的相关 SO 问题。 stackoverflow.com/questions/15739263/phantomjs-click-an-element/…
  • 嗯,this 脚本没有您描述的问题。请提供Minimal, Complete, and Verifiable example。最后的猜测:你退出得太早了。

标签: javascript phantomjs setinterval


【解决方案1】:

当我开始尝试 PhantomJS 时,我遇到了同样的问题。 我意识到问题可能是 page.evaluate() 正在打开的页面的上下文中运行。因此,当您单击登录按钮时,页面会被重定向,因此 click() 之后的语句不会被执行或输出不再可见。

我通过创建另一个 page.run() 块并在前一个块完成后运行它(即超时)解决了这个问题 - 因为我想在登录后执行脚本的那部分。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-29
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多