gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:23:18 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com