简体   繁体   中英

How to parse/map an html data table to a JSON object using CasperJS?

If I have a table with multiple rows and columns like:

<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>

I'm a little stumped on what CasperJS tools I should be using since I'm pretty sure I can't load any kind of parser or jQuery. I'd like to end up with a JSON object I can POST to a location, kinda like this:

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

How do I go about doing this in CasperJS?

CasperJS doesn't provide much help here. You will need to traverse the tree yourself. It's a good thing that DOM functions are quite capable. You will need to do this in the page context:

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));
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM