【问题标题】:casperjs jquery return data is nullcasperjs jquery返回数据为空
【发布时间】:2014-12-21 05:09:40
【问题描述】:

我在 casperjs 中使用了 jquery。 但返回数据为空。

检查过代码,但我不知道..

html代码是……

<table id="bd_lst" class="bd_lst">
<tr class="notice">
    <td class="cate">aaaaa</td>
    <td class="title"><a href="11111.html">11111</a></td>
</tr>
<tr class="notice">
    <td class="cate">bbbb</td>
    <td class="title"><a href="22222.html">22222</a></td>
</tr>
......................
<tr>
    <td class="cate">cccc</td>
    <td class="title"><a href="aaa.html">3333</a></td> <== i want return data "aaa.html"
</tr>
<tr>
    <td class="cate">ddddd</td>
    <td class="title"><a href="bbbb.html">4444</a></td>
</tr>
</table>

js 代码是....

var start_link = this.evaluate(function(){ 
    return $("#bd_list tr.notice").last().next().find(".title a").attr("href"); 
});

start_link 为空..

$("table tr.notice").last().next().find(".title a").attr("href") 在 html javascript 中返回 "aaa.html"..

怎么了?

【问题讨论】:

    标签: jquery return


    【解决方案1】:

    如果您只想检查第一个锚标记的 href 值,请使用:

    $('td.title > a').first().attr('href');
    

    使用 casperjs 抓取示例 DOM:

    var casper = require('casper').create();
    
    casper.start('http://my-site.com/examples/casperjs/sample.html', function() {
        var start_link = this.evaluate(function(){
            return document.querySelector('td.title > a').getAttribute('href');
        });
        this.echo(start_link);
    });
    
    casper.run();
    

    如果您想将 jQuery 与 casperjs 一起使用,您必须使用 clientScripts 选项使 jQuery 可用,如下所示:

    var casper = require('casper').create({
        verbose: true,
        clientScripts: ['jquery-1.9.1.min.js']
    });
    
    casper.start('http://my-site.com/examples/casperjs/sample.html', function() {
        var start_link = this.evaluate(function(){
            return $('td.title > a').first().attr('href');
        });
        this.echo(start_link);
    });
    
    casper.run();
    

    你使用过的选择器:

    $("#bd_lst tr.notice").last().next().find(".title a").attr("href"); 
    

    工作正常。您刚刚在输入表 id 时出错:它是 bd_lst 而不是 bd_list

    希望有用!

    【讨论】:

    • 谢谢..您的评论。但 html 代码是示例。问题不是 jquery 选择器,而是 casperjs 评估返回。我的 jquery 代码也可以工作。但不返回 casperjs 中的值。
    • @Kan:好的。您想使用 casper 进行抓取或测试吗?
    • @Kan:您的评估功能运行良好。您刚刚在 table'id 中输入错误:它是 bd_lst 而不是 bd_list
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-18
    • 2011-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-28
    • 1970-01-01
    相关资源
    最近更新 更多