Hi I'm Shendi
对于做爬虫来说,通常会遇到需要解析 html 的需求,而在 node.js 中,可以使用 Cheerio
来解析 html
非常简单,这里直接列出步骤
安装依赖
cnpm install cheerio
引入依赖
const cheerio = require('cheerio');
加载文档
通过 load
函数加载 dom
let doc = cheerio.load("<p><strong>hello,world</strong></p>");
cheerio的使用像JQuery那样,其中的doc可以命名为 $
,在使用时就与JQuery完全一致了
处理文档
加载完成后,通过返回的函数
来进行处理
其中函数是这样的,还包含了一些属性,例如text等
// 去掉标签获取内容 hello,world
console.log(doc.text());
在之前提到使用和JQuery一样,例如要获取所有的图片与文字
const cheerio = require('cheerio');
const html = `
<html>
<body>
<h1>标题</h1>
<p>这是一段文字。</p>
<img src="http://example.com/image.jpg" alt="示例图片">
<img src="http://example.com/image2.jpg" alt="示例图片2">
<p>还有更多文字。</p>
</body>
</html>
`;
let $ = cheerio.load(html);
console.log($.text());
let imgs = $("img");
console.log(imgs[0].attribs.src);
console.log(imgs[1].attribs.src);
// 同上
console.log($(imgs[0]).attr("src"));
console.log($(imgs[1]).attr("src"));
imgs.each((index, ele) => {
console.log($(ele).attr("src"));
});
END
本文链接:https://sdpro.top/blog/html/article/1232.html♥ 赞助 ♥
尽管去做,或许最终的结果不尽人意,但你不付出,他不付出,那怎会进步呢?