【问题标题】:How to get innerHTML using CasperJS?如何使用 CasperJS 获取 innerHTML?
【发布时间】:2015-12-10 20:46:49
【问题描述】:

我想在 HTML 页面的<em> 标记中仅获取字符串的属性

我想得到“(868)”

1.

casper.then(function() {
     var word = require('utils').dump(this.getElementAttribute(x('//*[@id="content"]/div[2]/h4/em'), 'em'));
     console.log(word)
});

2.

casper.then(function() {
    var word = require('utils').dump(this.getElementAttribute(h4[class="head"], 'em'));
    console.log(word)
});

我都试过了,但它返回“null”如何解决这个问题?

【问题讨论】:

    标签: javascript casperjs innerhtml


    【解决方案1】:

    <em> 不是元素属性。它本身就是一个元素。 casper.getElementAttribute(selector, attribute) 将正确检索元素的属性文本,但您想要获取元素文本。

    您可以为此使用casper.fetchText(selector)。请注意,fetchText() 会将所有匹配元素的内容连接到一个字符串中。如果你不想这样,你要么需要确保选择器只匹配单个元素,要么使用其他函数,例如casper.getElementInfo(selector).text


    您的第二个 sn-p 无法工作,因为您在选择器周围忘记了",并且由于上述原因。

    【讨论】:

    • 非常感谢。我使用了 casper.fetchText("h4.head em") 并且它有效。
    【解决方案2】:

    查看文档常见问题解答Can I access & manipulate DOM elements directly from the CasperJS environment?

    在您在问题中添加的两个示例中,您都试图将em 元素作为h4 的属性,这是错误的,因为em 是子元素,而不是h4 标记的属性,所以要选择元素的textContent,您可以尝试使用querySelectorevaluate 函数,如下所示:

    casper.then(function() {
        var text = this.evaluate(function(){
            return document.querySelector("h4.head em").textContent;
        });
    
        var word = require('utils').dump(text);
        console.log(word);
    }
    

    希望这会有所帮助。

    【讨论】:

    • @Zakaria Acharki 非常感谢!!但它返回字符串包括“”所以另一个答案更好。再次感谢您的回答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-05
    • 1970-01-01
    • 2011-12-13
    • 2012-06-09
    相关资源
    最近更新 更多