如何使用 cheerio 提取文本
How to extract text with cheerio
我正在尝试使用 NodeJS 和 Cheerio 从网站上抓取一些文本。我尝试了很多在网上找到的解决方案,但我的结果总是空的。
我要删除的网站:
https://www.bodybuilding.com/exercises/dumbbell-bench-press
相关HTML代码:
<div class="ExDetail" itemscope itemtype="http://schema.org/ExerciseAction">
<section class="ExDetail-section ExDetail-meta flexo-container flexo-start flexo-between">
<div class="grid-8 grid-12-s grid-12-m">
<h2 class="ExHeading ExHeading--h2 ExDetail-h2" itemprop="name">
Dumbbell Bench Press
</h2>
</div>
我正在尝试获取文本:哑铃卧推
但是我已经尽力了哈哈..
我当前的代码:
request(url, function(error, response, html) {
if (!error) {
var $ = cheerio.load(html);
var name = $('h2.ExHeading.ExHeading--h2.ExDetail-h2').text();
console.log(name);
var json = {
name: name
};
res.send(json);
}
});
编辑:
添加了 link 我正在尝试废弃。
答案:在 header 中添加虚假用户代理解决了问题!
我正在尝试使用 NodeJS 和 Cheerio 从网站上抓取一些文本。我尝试了很多在网上找到的解决方案,但我的结果总是空的。
我要删除的网站: https://www.bodybuilding.com/exercises/dumbbell-bench-press
相关HTML代码:
<div class="ExDetail" itemscope itemtype="http://schema.org/ExerciseAction">
<section class="ExDetail-section ExDetail-meta flexo-container flexo-start flexo-between">
<div class="grid-8 grid-12-s grid-12-m">
<h2 class="ExHeading ExHeading--h2 ExDetail-h2" itemprop="name">
Dumbbell Bench Press
</h2>
</div>
我正在尝试获取文本:哑铃卧推
但是我已经尽力了哈哈..
我当前的代码:
request(url, function(error, response, html) {
if (!error) {
var $ = cheerio.load(html);
var name = $('h2.ExHeading.ExHeading--h2.ExDetail-h2').text();
console.log(name);
var json = {
name: name
};
res.send(json);
}
});
编辑: 添加了 link 我正在尝试废弃。
答案:在 header 中添加虚假用户代理解决了问题!