使用phantom.js自动化浏览器

时间:2014-01-26 11:24:01

标签: javascript phantomjs

我正在尝试使用phantomjs自动化浏览器。我加载页面,提供登录凭据,然后单击提交按钮。作为第一步,我加载了一个页面,修改了表单值并将输出传送到.html文件以查看是否有效。这是我的代码:

var page = require('webpage').create();
var fs = require('fs');
page.onConsoleMessage = function(msg) {
  fs.write("/home/phantom/output.html", msg, 'w');
};
page.settings.userAgent = 'SpecialAgent';
//page.open('http://google.com', function(status) {
page.open('https://somewebsitehavingaform.com', function(status) {
  if (status !== 'success') {
    console.log('Unable to access network');
  } else {
    var ua = page.evaluate(function() {
        document.getElementsByName('id').value="id";
        document.getElementsByName('name').value="name";    
        document.getElementsByName('password').value="password";        
        console.log(document.body.innerHTML);
    });
  }
  phantom.exit();
});

当我打开output.html时,它会向我显示表单但它是空的。我希望预先填写id,name和密码。我在哪里错了?

1 个答案:

答案 0 :(得分:1)

首先,getElementsByName将返回一个数组。为了设置使用该名称找到的第一个输入的值,您需要选择其中的特定元素,即第一个:

getElementsByName('foo')[0].value = 'bar'

然后,如果您更改分配以使用setAttribute,它似乎正常工作:

var ua = page.evaluate(function() {
    document.getElementsByName('id')[0].setAttribute("value", "id");
    document.getElementsByName('name')[0].setAttribute("value", "name");
    document.getElementsByName('password')[0].setAttribute("value", "password");
    console.log(document.body.innerHTML);
});

根据Mozilla docs

  

使用setAttribute()修改某些属性,最值得注意的是值   在XUL中,工作不一致,因为属性指定了默认值   值。要访问或修改当前值,您应该使用   属性。例如,使用elt.value代替   elt.setAttribute('value', val)

虽然您只是将生成的HTML写入文件,但我认为在这种情况下我不会认为它会引起您的问题。

不确定Phantom JS现在是否在内部使用QJSEngine,但请注意其待办事项上的this open ticket,这可能与您使用点符号获得的问题有关:

  

QJSEngine是V8的简单包装器,主要用于QtQml。   使用QJSEngine作为PhantomJS主要上下文可能会更多   可扩展/可定制的当前实现。

     

问题:

     

...

     

使用点表示法时自动创建属性不适用于添加到QJSEngine的QObject

(这表明QJSEngine不是当前正在使用的实现,但是在9个月前被提出,所以不确定它是否自那时起被引入,所以认为值得标记)

相关问题