javascript - 使用nodejs和cheerio从html解析表

标签 javascript html node.js parsing 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>

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

但是响应是空的。

最佳答案

我会给你一个基于我在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了解更多示例。

关于javascript - 使用nodejs和cheerio从html解析表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47831382/

相关文章:

javascript - 使用javascript?

JavaScript : "event is sent to an element" -

node.js - Socket.io 是否可以与 Heroku 一起使用?

javascript - 意外的标记,-asp 值显示为未定义

javascript - 很难通过属性选择节点的子节点

javascript - 如何在 angular.js 中使用可靠的 ddl

javascript - Codepen 在 HTML 上工作而不在 ASP.NET 上工作

javascript - 在 Meteor 中使用具有依赖项的 NPM 包

javascript - 在 API 帖子中注册用户时设置电子邮件和用户名的多重验证

javascript - 如何运行依赖于第一个 api 中设置的变量的 api?