phantomjs中的元素为null [英] null for elements in phantomjs

查看:113
本文介绍了phantomjs中的元素为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在phantomjs中运行了这段代码.我不知道为什么form.elements总是向我返回null.我在chrome开发人员控制台上运行了相同的代码,并得到了我想要的正确结果.

I have this code running in the phantomjs. I don't know why form.elements keeps returning null to me. I ran the same code on chrome developer console and got the right result i want.

我对javascript和所有相关内容还很陌生.请说明一下.

I'm pretty new to javascript and everything related. Please shed some light.

var page = require('webpage').create();
page.open('http://www.kayak.com', function (status) {
    if (status !== 'success') {
        console.log('Unable to access network');
    } else {
        var form = page.evaluate(function(){
             return document.getElementById('searchform');
        });
        console.log(form.elements[2].value);
    }
    phantom.exit();
});

推荐答案

您不能通过evaluate传递非原始对象.在文档中提到:

You can't pass a non-primitive object through evaluate. This is mentioned in the documentation:

注意:参数和评估函数的返回值必须是一个简单的原始对象.经验法则:如果可以通过JSON序列化,那就很好.闭包,函数,DOM节点等将无法正常工作!

Note: The arguments and the return value to the evaluate function must be a simple primitive object. The rule of thumb: if it can be serialized via JSON, then it is fine. Closures, functions, DOM nodes, etc. will not work!

尽管这是使用PhantomJS时最常见的错误,但这很容易解决.只要确保在evaluate中尽可能多地执行所有处理,然后返回一个简单的对象即可.有关详细信息,请仔细研究文档,并从所有包含的

Although it is the most common mistake when using PhantomJS, this is rather easy to solve. Just make sure you do all the processing as much as you can within evaluate and then return back a simple object. For details, please study the documentation carefully and learn from all the included examples.

这篇关于phantomjs中的元素为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆