很难用 Cheerio 抓取一个单元格
Having hard time scraping a cell with Cheerio
我正在尝试从 table 中抓取一个单元格,但我遇到了困难,我可能做错了什么,因为我在控制台中得到了一个空结果(实际上什么都没有)。
这是HTML:
我正在尝试获取 <td class="center bold storing_1">1</td>
。
这是我的代码:
const rp = require('request-promise');
const cheerio = require('cheerio');
const url = 'MY URL';
rp(url)
.then(function(html) {
$ = cheerio.load(body);
console.log($('#table_results tbody tr:nth-child(1) td.center.bold.sorting_1')).text();
})
.catch(function(err) {
});
感谢任何帮助!谢谢!
我觉得你的代码其实没问题,我觉得你只是有几个错别字而已。
- 您正在解析 'body' 而不是 'html'
- 您正在从 console.log() 而不是 cheerio 对象 ($).
的结果中读取 .text()
如果您尝试下面的代码,它应该可以工作:
const rp = require('request-promise');
const cheerio = require('cheerio');
const url = 'MY URL';
rp(url).then(function(html) {
$ = cheerio.load(html);
console.log("Result:", $('#table_results tbody tr:nth-child(1) td.center.bold.sorting_1').text());
})
.catch(function(err) {
console.error("An error occurred:", err);
});
Html 我正在测试:
测试html
<table id="table_results">
<thead></thead>
<tbody>
<tr ajax-controller="community">
<td class="center bold sorting_1">1</td>
<td class="center bold sorting_1">2</td>
</tr>
</tbody>
</table>
简单的测试设置:
您可以尝试一下,看看编辑选择器有何改变:
const testHtml =
`<table id="table_results">
<thead></thead>
<tbody>
<tr ajax-controller="community">
<td class="center bold sorting_1">1</td>
</tr>
</tbody>
</table>`;
$ = cheerio.load(testHtml);
console.log("Result:", $('#table_results tbody tr:nth-child(1) td.center.bold.sorting_1').text());
我正在尝试从 table 中抓取一个单元格,但我遇到了困难,我可能做错了什么,因为我在控制台中得到了一个空结果(实际上什么都没有)。
这是HTML:
我正在尝试获取 <td class="center bold storing_1">1</td>
。
这是我的代码:
const rp = require('request-promise');
const cheerio = require('cheerio');
const url = 'MY URL';
rp(url)
.then(function(html) {
$ = cheerio.load(body);
console.log($('#table_results tbody tr:nth-child(1) td.center.bold.sorting_1')).text();
})
.catch(function(err) {
});
感谢任何帮助!谢谢!
我觉得你的代码其实没问题,我觉得你只是有几个错别字而已。
- 您正在解析 'body' 而不是 'html'
- 您正在从 console.log() 而不是 cheerio 对象 ($). 的结果中读取 .text()
如果您尝试下面的代码,它应该可以工作:
const rp = require('request-promise');
const cheerio = require('cheerio');
const url = 'MY URL';
rp(url).then(function(html) {
$ = cheerio.load(html);
console.log("Result:", $('#table_results tbody tr:nth-child(1) td.center.bold.sorting_1').text());
})
.catch(function(err) {
console.error("An error occurred:", err);
});
Html 我正在测试:
测试html
<table id="table_results">
<thead></thead>
<tbody>
<tr ajax-controller="community">
<td class="center bold sorting_1">1</td>
<td class="center bold sorting_1">2</td>
</tr>
</tbody>
</table>
简单的测试设置:
您可以尝试一下,看看编辑选择器有何改变:
const testHtml =
`<table id="table_results">
<thead></thead>
<tbody>
<tr ajax-controller="community">
<td class="center bold sorting_1">1</td>
</tr>
</tbody>
</table>`;
$ = cheerio.load(testHtml);
console.log("Result:", $('#table_results tbody tr:nth-child(1) td.center.bold.sorting_1').text());