【问题标题】:How to use getElementByXpath and getElementsByXpath correctly?如何正确使用 getElementByXpath 和 getElementsByXpath?
【发布时间】:2026-01-07 03:45:01
【问题描述】:

如何使用 CasperJS 获取表 '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 获取表值。首先,我需要选择表格的行;然后我想得到'td'值。我该如何解决这个问题?

我尝试了很多方法,但都没有奏效。我的解决方案看起来与您在下面看到的类似。重要的是,首先选择'table_rows';然后在 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;
}

【问题讨论】:

    标签: javascript html web-scraping casperjs


    【解决方案1】:

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

    __utils__.getElementsByXpath()__utils__.getElementByXpath() 仅在 casper 不可用的页面上下文中可用。这两个函数直接返回 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));
    });
    

    您可以使用childrenquerySelector()document.evaluate() 等所有方式遍历DOM。

    1 另请阅读PhantomJS documentation of the same function

    【讨论】: