【问题标题】:How to get href attribute value in CasperJS?如何在 CasperJS 中获取 href 属性值?
【发布时间】:2014-12-31 04:24:29
【问题描述】:

这是我使用代码获取元素内的 href 值的方法:

var info = this.getElementsInfo(selector); // an array of object literals
for (var i = firstp; i < info.length; i=i+interval) {
    if(i==0)
        this.echo('"'+info[i].getAttribute('href')+'"');
    else
        this.echo(',"'+info[i].getAttribute('href')+'"');
}

【问题讨论】:

    标签: javascript attributes web-crawler casperjs


    【解决方案1】:

    我在documentation 中找到了一些东西,我可以用这样的代码解决我的问题:

    var info = this.getElementsInfo(selector); // an array of object literals
    for (var i = firstp; i < info.length; i=i+interval) {
        if(i==0)
            this.echo('"'+info[i].attributes.href+'"');
        else
            this.echo(',"'+info[i].attributes.href+'"');
    }
    

    现在可以使用了。

    它以前不能与getAttribute 一起工作的原因是casper.getElementsInfo() 返回 DOM 节点的普通对象表示,而不是实际的 DOM 节点。由于 CasperJS(以及就此而言的 PhantomJS)有两个上下文,因此 DOM 节点不能传递到页面上下文之外(在 casper.evaluate() 内)。

    【讨论】:

    • 没关系。当你写一个答案时,添加一个描述为什么会这样总是好的。我为您添加了一个主题更广泛的主题。
    【解决方案2】:

    按照以下步骤操作:

    先获取路径

    some variable = 'table#dgResults > tbody > tr:nth-child(1) > td > b a';
    

    它去了(这只是对“一些变量”的解释):

    table[id="dgResults"] -> (couldn't add to the stupid gray box)
    
        tbody
    
          tr-> lst column
    
              b
                  a -> all href tags are here 
    

    接下来使用getElementsAttribute

    var nextStep = this.getElementsAttribute(elem, 'href');
    

    然后转储它:

    utils.dump(nextStep);
    

    当您转储它时,您应该会看到所有链接。请记住,this.getElementAttribute() 在标签之间返回 1 个值,this.getElementsAttribute() 在标签之间返回所有值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-11
      • 1970-01-01
      • 1970-01-01
      • 2022-11-18
      • 2013-10-03
      • 1970-01-01
      • 1970-01-01
      • 2016-06-07
      相关资源
      最近更新 更多