如何正确使用 getElementByXpath 和 getElementsByXpath?

How to use getElementByXpath and getElementsByXpath correctly?

如何使用 CasperJS 获取 table 'td' 值?

HTML 来源看起来像这样:

<table id="my_table">
  <tr id='header'>
    <th>sth_head_name</th>
    <th>ath_head_name</th>
    <th>sth_head_name</th>
    <th>sth_head_name</th>
    <th>sth_head_name</th>
  </tr>
  <tr>
    <td>sth_value</td>
    <td>sth_value</td>
    <td>sth_value</td>
    <td>sth_value</td>
    <td>sth_value</td>
  </tr>
  <tr>
    <td>sth_value</td>
    <td>sth_value</td>
    <td>sth_value</td>
    <td>sth_value</td>
    <td>sth_value</td>
  </tr>
  <tr>
    <td>sth_value</td>
    <td>sth_value</td>
    <td>sth_value</td>
    <td>sth_value</td>
    <td>sth_value</td>
  </tr>
</table>

我想使用 CasperJS 获取 table 值。首先,我需要 select table 的行;然后我想获得 'td' 值。我该如何解决?

我尝试了很多方法,但都没有用。我的解决方案看起来与您在下面看到的类似。重要的是,首先 select 'table_rows';然后 select 这是 for 循环中的 td 值。

var table_rows = casper.getElementsByXpath("//table[@id='my_table']/tr[not(@id='header')]");

for (var i = 0; i < table_rows.length; i++) {
  var firstRequiredCell_query = table_rows[j].getElementByXpath("//td[position()=2]");
  var secondRequiredCell_query = table_rows[j].getElementByXpath("//td[position()=4]");
  var firstRequiredCell = firstRequiredCell_query.text;
  var secondRequiredCell = secondRequiredCell_query.text;
}

CasperJS 有两个上下文。您只能直接从您可以访问 casper.evaluate()1 内部的页面上下文访问 DOM。它是沙盒化的,因此在外部定义的变量在 evaluate() 中不可用。

__utils__.getElementsByXpath()__utils__.getElementByXpath() 仅在 casper 不可用的页面上下文中可用。这两个函数 return DOM 直接指向节点,因此这些节点本身没有 getElementByXpath() 函数。

但你根本不需要:

casper.then(function(){
    var info = this.evaluate(function(){
        var table_rows = __utils__.getElementsByXpath("//table[@id='my_table']/tr[not(@id='header')]");

        return table_rows.map(function(tr){
            return {
                a: tr.children[1].textContent,
                b: tr.children[3].textContent
            };
        });
    });
    this.echo(JSON.stringify(info, undefined, 4));
});

您可以使用所有方式遍历 DOM,例如 childrenquerySelector()document.evaluate()

1 请同时阅读 PhantomJS documentation of the same function.