如何使用 CasperJS 从此 tr 中找到的文本检索 tr id

How to retrieve tr id from a text found in this tr with CasperJS

今天的这个问题是关于如何使用 CasperJS 从之前在 tr 中找到的文本中检索 tr id。

示例 - 以下页面代码:

在上面的页面代码中,我们有更多 tr 的 ID 为 "connectedToNeType[0]}_TR",但编号与 0..15.

不同

我的目标是通过文本 "ABC_123" 搜索并找到相应的 ID。 第一部分找到 "ABC_123" 我用下面的代码管理:

casper.then(function() {
    var xpath = '//*[contains(text(), "ABC_123")]';
    var found = this.evaluate(function(xp) {
        return __utils__.getElementByXPath(xp);
    }, xpath);
    if (found === null) {
        this.echo("-> NOT FOUND");
        this.die();
    };
    this.echo("FOUND");
...

但是我怎样才能从这一点找到相应的 tr id 呢?

CasperJS 具有与 PhantomJS 相同的限制。页面上下文是沙盒的,您只能将原始对象传入和传出。 DOM 节点不是原始对象,这就是为什么它被 return 编辑为 null。见 documentation:

Note: The arguments and the return value to the evaluate function must be a simple primitive object. The rule of thumb: if it can be serialized via JSON, then it is fine.

Closures, functions, DOM nodes, etc. will not work!

您必须return表示您感兴趣的元素。如果您做不到,那么您必须完成所有工作在页面上下文中。

您似乎想要 select <tr> 元素,它是包含您拥有的文本的 <td> 元素的父元素。 XPath 支持匹配 .. 的子项的父项。你可以简单地这样做:

casper.then(function() {
    var xpath = '//td[contains(text(), "ABC_123")]/..';
    var foundId = this.evaluate(function(xp) {
        return __utils__.getElementByXPath(xp).id;
    }, xpath);
    if (foundId == null) {
        this.echo("-> NOT FOUND");
        this.die();
    };
    this.echo("FOUND: " + foundId);
});

或与其他功能:

var x = require("casper").selectXPath;
...
casper.then(function() {
    var xpath = '//td[contains(text(), "ABC_123")]/..';
    var foundId = this.getElementAttribute(x(xpath), "id");
    if (foundId == null) {
        this.echo("-> NOT FOUND");
        this.die();
    };
    this.echo("FOUND: " + foundId);
});