【问题标题】:How to select specified element with CasperJS?如何使用 CasperJS 选择指定元素?
【发布时间】:2018-01-13 09:38:33
【问题描述】:

我想先选择 <span> 和第二个 <span> ,然后获取它们的 innerText。

我尝试使用 xpath 或 document.querySelector ,它们不起作用。我console.log我的数组显示为空。

// I want to select first <span>
function getDate() {
    var date = document.querySelector('div.movie_intro_info_r li').selectedIndex = 1;
    return Array.prototype.map.call(date, function (e) {
        return e.innerHTML;
    });
};
// I want to select second <span>
function getMovieLength() {
    var movieLength = document.querySelectorAll(x('//*[@class="movie_intro_info_r"]/span[2]'));
    return Array.prototype.map.call(movieLength, function (e) {
        return e.innerText;
    });
};

casper.then(function () {
    casper.each(movieHref, function (casper, url) {
        casper.thenOpen(url, function () {
            casper.waitForSelector('div.btn_gray_info.gabtn', function () {
                console.log('wait for element');
            });
            releaseDate[urlCount] = this.evaluate(getDate);
            console.log(releaseDate[urlCount]);// show null

            movieLength[urlCount] = this.evaluate(getMovieLength);
            console.log(movieLength[urlCount]);// show null
            urlCount++;
        });
    });
});

我怎样才能只选择指定的元素并获取它的innerText?

【问题讨论】:

    标签: javascript css-selectors phantomjs casperjs selectors-api


    【解决方案1】:

    你的代码对于你想要做的事情来说有点太复杂了。您应该考虑将 fetchText 方法与 CSS 选择器一起使用:

    var casper = require('casper').create();
    
    casper.start('YOUR_URL', function () {
      this.echo(this.fetchText('.movie_intro_info_r > span:first-of-type'));
      this.echo(this.fetchText('.movie_intro_info_r > span:nth-of-type(2)'));
    }).run();
    

    【讨论】:

    • 非常感谢您的回复,我试试您的代码 google fetchText 查看 API 和 stackoverflow 中的其他代码。我仍然无法打印任何东西,我更新了我在我的问题上尝试的代码。你能检查我的代码并给我建议我应该采取什么步骤吗?非常感谢!
    • 我尝试检查它是否存在 ' if (this.exists('.movi​​e_intro_info_r > span:nth-of-type(2)')) { console.log('yes') ; } else { console.log('no'); }' 打印编号。
    • 现在没问题了,原因是我根据你的建议把代码放错了地方。谢谢你的帮助,祝福。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-06
    • 1970-01-01
    • 2011-10-10
    • 1970-01-01
    • 2016-03-24
    • 2015-04-28
    • 2015-02-10
    相关资源
    最近更新 更多