【问题标题】:Parse table from html using nodejs and cheerio使用nodejs和cheerio从html解析表
【发布时间】:2018-05-29 14:34:16
【问题描述】:

我在将 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>

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

但是响应是空的。

【问题讨论】:

  • 你检查你的html变量了吗?它真的包含你需要的html吗?另外,我认为你应该在使用选择器时在类名中添加点——比如$(".testinformation")
  • @profiler 你试过 $(".testinformation") 吗?正如jehy所说
  • 结果也是空的 - [].
  • @Jehy,你有什么想法吗?
  • 抱歉,我没有想法,需要更多数据 - 例如,源数据或 html。

标签: javascript html node.js parsing cheerio


【解决方案1】:

我会根据我在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);
 })  
}

在 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

【讨论】:

  • 谢谢,但我正在搜索与我的案例的联系。你能粘贴html表格源吗?
猜你喜欢
  • 1970-01-01
  • 2015-09-01
  • 1970-01-01
  • 2015-10-07
  • 1970-01-01
  • 2013-03-06
  • 1970-01-01
  • 2017-10-31
  • 2015-06-18
相关资源
最近更新 更多