【问题标题】:How to parse/map an html data table to a JSON object using CasperJS?如何使用 CasperJS 将 html 数据表解析/映射到 JSON 对象?
【发布时间】:2016-03-18 18:21:57
【问题描述】:

如果我有一个包含多行和多列的表格,例如:

<tr>
  <td></td>
  <td><input class="chkdummyclass" id="105" name="checkBox" type="checkbox"
  value="true"><input name="checkBox" type="hidden" value="false"></td>
  <td>94</td>
  <td></td>
  <td>3VW637AJ3VINNUMBEr</td>
  <td>Used</td>
  <td>2014</td>
  <td>Volkswagen</td>
  <td>Jetta Sedan</td>
  <td>Trendline/Comfortline/Highline</td>
  <td>4dr Hybrid TSI DSG Trendline</td>
  <td></td>
  <td class="rightAlign">0</td>
  <td class="rightAlign">
    $22,919.00
  </td>
  <td class="rightAlign">$11,999.00</td>
  <td>Available</td>
  <td>
    0
  </td>
  <td>
    <a href="javascript:;" onclick=
    "javascript:GetVehicleImages(105,0);">0/20</a>
  </td>
  <td class="centerAlign"><img src=
  "/inventory/Configured.png"></td>
</tr>

我对我应该使用哪些 CasperJS 工具感到有些困惑,因为我很确定我无法加载任何类型的解析器或 jQuery。我想最终得到一个可以 POST 到某个位置的 JSON 对象,有点像这样:

{
  'vin': '3VW637AJ3VINNUMBEr',
  'make': 'Volkswagen',
  'year': 2014
 // etc
}

如何在 CasperJS 中执行此操作?

【问题讨论】:

    标签: javascript jquery html css-selectors casperjs


    【解决方案1】:

    CasperJS 在这里没有提供太多帮助。您将需要自己遍历树。好在 DOM 函数功能强大。您需要在页面上下文中执行此操作:

    casper.then(function(){
        var info = this.evaluate(function(){
            var table_rows = document.querySelectorAll("tr"); //or better selector
    
            return Array.prototype.map.call(table_rows, function(tr){
                return {
                    vin: tr.children[4].textContent,
                    make: tr.children[7].textContent,
                    year: tr.children[6].textContent
                };
            });
        });
        this.echo(JSON.stringify(info, undefined, 4));
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-02
      • 2019-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      相关资源
      最近更新 更多