Javascript 使用nodejs和cheerio从html解析表
我在将html表解析为json时遇到问题 Htlm表格页:Javascript 使用nodejs和cheerio从html解析表,javascript,html,node.js,parsing,cheerio,Javascript,Html,Node.js,Parsing,Cheerio,我在将html表解析为json时遇到问题 Htlm表格页: <div id="content"> <h1>content-information</h1> <table class="testinformation"> <thead> <tr> <th>hello</th>
<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>
但是回答是空的。我将根据我在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检索数据
以上是API代码。请参阅以获取更多示例。我将根据我在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检索数据
以上是API代码。请参阅以获取更多示例。是否检查了
html
变量?它真的包含你需要的html吗?另外,我认为在使用选择器时,应该在类名中添加点,例如$(“.testinfo”)
@profiler您尝试过$(“.testinfo”)?正如jehy saidAlso所说,结果是空的-[]。@jehy,你有什么想法吗?对不起,我没有想法,需要更多数据-例如,源数据或html。你检查了html
变量了吗?它真的包含你需要的html吗?另外,我认为在使用选择器时,应该在类名中添加点,例如$(“.testinfo”)
@profiler您尝试过$(“.testinfo”)?正如jehy saidAlso所说,结果是空的-[]。@jehy,你有什么想法吗?对不起,我没有想法了,需要更多数据-例如,源数据或html。谢谢,但我正在搜索与我的案例的连接。你能粘贴html表格源代码吗?谢谢,但我正在搜索与我的案例的连接。你能粘贴html表格源代码吗?