PhantomJS获取属性

时间:2017-06-10 10:34:38

标签: javascript jquery phantomjs

如果我有这个:

<video data-autostart="false" data-src="http://example.com/1.mp4">

我收到以下错误:

  

TypeError:undefined不是对象

以下是我的JavaScript代码:

var page = require( 'webpage' ).create();
    var url = 'http://example.com/';
    page.open(url, function( status ) {
        if ( status === 'success' ) {
        page.includeJs('https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js', function() {
            var link = page.evaluate(function() {
                return $( 'video[data-autostart="false"]' ).attr( 'data-src' );
            });
            console.log( link );
            phantom.exit();
        });
    } else {
        console.log( 'FAIL' );
    }
});

我做错了什么,如何解决?

1 个答案:

答案 0 :(得分:1)

你几乎做的一切都是正确的,但是当你在脚本中访问它时,你所寻找的元素显然不存在。

因此错误,undefined不是对象。您尝试访问的元素未定义,不存在。

您可以在访问之前检查元素是否存在:

var link = page.evaluate(function() {
    if($( 'video[data-autostart="false"]' ).length != 0)
    {
        return $( 'video[data-autostart="false"]' ).attr( 'data-src' );
    }
    else
    {
        return false;
    }
});

if (link === false) {
    console.log("Video not found!");
    phantom.exit(1); // Error exit code
}

完整的工作示例:

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

page.open(url, function( status ) {
    if ( status === 'success' ) {
        page.includeJs('https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js', function() {
            var link = page.evaluate(function() {
                if($( 'video' ).length != 0)
                {
                    return $( 'video' ).attr('preload');
                }

            });
            console.log( link );
            phantom.exit();
        });
    } else {
        console.log( 'FAIL' );
    }
});

打印

  

元数据