首先有node,然后是引入模块,这是必备
fs模块写入文件
path模块定义文件路径
request模块定义发送请求(requests可能要好点,各位如果需要改的自行百度)
cheerio模块定义内容加载成DOM(个人理解)
(不需要把内容转换成文本的可以不需要fs,psth模块)
这里我是需要网页中meta标签中的值
let fs = require('fs') // 读写文件 let path = require('path') // 定义文件路径 var request = require('request'); var cheerio = require('cheerio'); var options = { 'url': 'https://mp.weixin.qq.com/s/P8q3CjZdH-GCtB2VHVy_qg', 'headers': { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36", } }; request(options, function(error, response, body) { if (error) throw new Error(error); // console.log(body); // fs.writeFile(path.resolve(__dirname, 'index.html'), body, () => { //将请求得到的资源文件写入本地项目文件夹下的index.html(名字可改)中 // console.log("保存成功") // 数据爬取成功,输出“保存成功” // }) getdom(body) }); function getdom(html) { var $ = cheerio.load(html); //后面就像用jq一样获取页面元素就可以了 // var a = $('meta').slice(last, last - 8) var obj = {} var desc = $('[name=description]').attr('content') var title = $('[property=og:title]').attr('content') var img = $('[property=og:image]').attr('content') // console.log(desc); // console.log(title); // console.log(img); obj = { 'desc': desc, 'title': title, 'img': img } console.log(obj); fs.writeFile(path.resolve(__dirname, 'data.html'), html // 转换JSON格式 , () => { console.log("保存成功") }) }
这是获取到网页的指定内容
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律