最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

使用nodejs和cheerio从html解析表

运维笔记admin10浏览0评论

使用nodejs和cheerio从html解析表

使用nodejs和cheerio从html解析表

我有解决html表到json的问题。

Html表页面:

  <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="">hello1</a></td>
                <td><a href="">test_text</a></td>
            </tr>
            <tr>
                <td><a href="">hello2</a></td>
                <td><a href="">test_text2</a></td>
            </tr>            
        </tbody>
    </table>
  </div>

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

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


request('', 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',我将在其他函数中使用它来从中检索数据。

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

在cardIac()函数中,我使用主HTML()函数从#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";
 scraper.mainHtml(url, function(parsedHTML){
    scraper.cardDiv(parsedHTML,function(parsedData) {

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

以上是API代码。有关更多示例,请参阅cheerio。

发布评论

评论列表(0)

  1. 暂无评论