js抓取网页内容(什么是jQuery的HTTP模块?以及如何使用? )
优采云 发布时间: 2021-12-08 04:04js抓取网页内容(什么是jQuery的HTTP模块?以及如何使用?
)
一、基本思路
首先找一个网址:因为这是http协议,所以需要用到node.js的http模块,我们使用http模块中的get()方法来抓取。其中,如果我们不需要捕获所有的数据,而只需要部分数据,比如某个类下的a标签中的文本,那么如果我们在前端,就可以使用DOM操作找到这个节点,但是node.js中没有DOM操作,所以这里需要用到cheerio库。既然抓到了网站上的数据,就涉及到文件的写入,此时需要用到node.js中的fs模块。
二、学习网址
cheerio 官方学习文档cheerio npm 网站 node.js 官方文档 node.js 中文文档
二、cheerio 是什么以及如何使用
Cheerio 是为服务器设计的核心 jQuery 的快速、灵活和精益实现。他可以像jquery一样操作字符串。
安装cheerio
npm install cheerio
具体用途
const cheerio = require('cheerio')
const $ = cheerio.load('Hello world')
$('h2.title').text('Hello there!')
$('h2').addClass('welcome')
$.html()
//=> Hello there!
三、具体代码
const http = require("http");
const fs = require("fs");
const cheerio = require("cheerio");
http.get("http://tech.ifeng.com/", function(res) {
// 设置编码
res.setEncoding("utf8");
// 当接收到数据时,会触发 "data" 事件的执行
let html = "";
res.on("data", function(data){
html += data;
});
// 数据接收完毕,会触发 "end" 事件的执行
res.on("end", function(){
// 待保存到文件中的字符串
let fileData = "";
// 调用 cheerio.load() 方法,生成一个类似于 jQuery 的对象
const $ = cheerio.load(html);
// 接下来像使用 jQuery 一样来使用 cheerio
$(".pictxt02").each(function(index, element) {
const el = $(element);
let link = el.find("h3 a").attr("href"),
title = el.find("h3 a").text(),
desc = el.children("p").text();
fileData += `${link}\r\n${title}\r\n\t${desc}\r\n\r\n`;
});
// console.log("读取结束,内容:");
// console.log(html);
fs.writeFile("./dist/source.txt", fileData, function(err) {
if (err)
return;
console.log("成功")
});
})
});