【问题标题】:How to retrieve attribute of element in CasperJS using an XPath expression如何使用 XPath 表达式在 CasperJS 中检索元素的属性
【发布时间】:2012-07-07 18:13:32
【问题描述】:

我有一个网页,两行之间有这个:

<a href="http://foo.com/home.do?SID=3443132">...

我需要使用 XPath 提取“href”属性。在 CasperJS 的 API 中写了这样的信息:clientutils.getElementByXPath

这是我的代码:

phantom.casperPath = '..n1k0-casperjs-5428865';
phantom.injectJs(phantom.casperPath + '\\bin\\bootstrap.js');

var casper = require('casper').create();

var url = "...";

casper.start(url, function() {
casper.echo("started");
});

var x = require('casper').selectXPath;           

casper.then(function() 
{
casper.echo("getsid");  
    this.test.assertExists(x('//a[contains(@href, "home.do?SID=")]'), 'the element exists');
var element = __utils__.getElementByXPath('//a[contains(@href, "home.do?SID=")]');    
});

但它失败了。它返回这个:

false
undefined
started
getsid
PASS the element exists  <== XPATH WORKS
FAIL ReferenceError: Can't find variable: __utils__
#    type: uncaughtError
#    error: "ReferenceError: Can't find variable: __utils__"
ReferenceError: Can't find variable: __utils__

【问题讨论】:

  • 你不能在 casperjs 环境中直接使用__utils__。您必须使用Casper.evaluate() 方法。
  • @videador 你能说明你是如何解决这个问题的吗?

标签: javascript xpath phantomjs casperjs


【解决方案1】:

试试这个:

phantom.casperPath = '..n1k0-casperjs-5428865';
phantom.injectJs(phantom.casperPath + '\\bin\\bootstrap.js');

var url = "...";
var casper = require('casper').create();
var x = require('casper').selectXPath;

casper.start(url, function() {

 casper.echo("started");

});      

casper.then(function() {

 casper.echo("getsid");  

 var xpath = '//a[contains(@href, "home.do?SID=")]';
 var xpath_arr = { type: 'xpath', path: xpath};

 this.test.assertExists(xpath_arr, 'the element exists');

 var element = x(xpath);    
});

【讨论】:

  • x() 不检索元素。它只是创建与您手动创建为 xpath_arr 完全相同的对象。
【解决方案2】:

正如 cmets 中所指出的,您必须在 evaluate 回调中使用 __utils__,因为它被注入到页面中。既然你想要(ed)href,你可以使用:

casper.then(function(){
    casper.echo("getsid");  
    this.test.assertExists(x('//a[contains(@href, "home.do?SID=")]'), 'the element exists');
    var href = this.evaluate(function(){
        var element = __utils__.getElementByXPath('//a[contains(@href, "home.do?SID=")]');
        return element.href;
    });
});

这可以通过使用casper.getElementAttribute来缩短:

casper.then(function(){
    casper.echo("getsid");  
    this.test.assertExists(x('//a[contains(@href, "home.do?SID=")]'), 'the element exists');
    var href = this.getElementAttribute(x('//a[contains(@href, "home.do?SID=")]'), "href");
});

您还可以使用casper.getElementInfo 获取元素的完整信息,包括所有属性(但只有一些属性)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-13
    • 1970-01-01
    • 1970-01-01
    • 2021-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多