繁体   English   中英

使用nodejs和cheerio从html解析表

[英]Parse table from html using nodejs and cheerio

我在将html表解析为json时遇到问题。

Htlm表页面:

  <div id="content">
    <h1>content-information</h1>
              <table class="testinformation">
        <thead>
            <tr>
                <th>hello</th>
                <th>test_text</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td><a href="https://example.com">hello1</a></td>
                <td><a href="https://example.com/test_text">test_text</a></td>
            </tr>
            <tr>
                <td><a href="https://example.com">hello2</a></td>
                <td><a href="https://example.com/test_text2">test_text2</a></td>
            </tr>            
        </tbody>
    </table>
  </div>

节点js / cheerio脚本,它无法正常工作:

  var cheerio = require('cheerio'),
cheerioTableparser = require('cheerio-tableparser');
const request = require('request');


request('https://correct-url.com', function (error, response, html) {
  if (!error) {
    const $ = cheerio.load(html)
    cheerioTableparser($);
    var data = $("testinformation").parsetable();
    console.log(data);
  }
})

但是响应是空的。

我将基于我在cheerio上的工作为您提供示例,这可能对您有所帮助

var cheerio = require('cheerio');
var request = require('request');

 function mainHtml(url, callback){
  request(url,function(error,response,html) {
    console.log(url);
    var $ =cheerio.load(html);

    $('#saleS').each(function(i,element){
        var data = $(this);
        var parsedHTML = data.html();
        callback(parsedHTML);
    });  
  });
 }

我做了一个回调函数,其中包括我需要抓取的数据的主要div。 mainHTML()函数返回“ HTML”,我将在其他函数中使用“ HTML”从中检索数据。

 function cardDiv(parsedHTML, callback){
 var $ = cheerio.load(parsedHTML);
 $(' #resultBlockWrapper').each(function(i,element){
     var data = $(this);
     var parsedData = data.children().text();
     callback(parsedData);
 })  
}

在cardDiv()函数中,我使用mainHTML()函数从#saleS div的子级div中检索了数据。

var express = require('express');
var app = express();
var router = express.Router();
var scraper = require('./scraper');

router.get('/scrape', function (req, res) {

https: url = "https://www.example.com";
 scraper.mainHtml(url, function(parsedHTML){
    scraper.cardDiv(parsedHTML,function(parsedData) {

      console.log(n + " " +parsedData);     
   })
 }); 

上面是API代码,请参阅cheerio以获取更多示例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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