前言
本文使用node以爬取百度新闻为例展示node爬虫技术。
需求:能看懂html网页结构,知道自己想要哪里。
需求:能看懂html网页结构,知道自己想要哪里。
需求:能看懂html网页结构,知道自己想要哪里。
正文
1.再vscode中新建文件夹,右键文件夹选择集成终端中打开
2.输入初始化命令:npm init -y
3.安装express 模块:npm i express
4.安装got模块:npm i got
5.安装cheerio模块:npm i cheerio
安装完成应显示:
6.代码部分:
app.get('/p', (req, res) => { //定义路由
(async () => {
try {
const response = await got('https://news.baidu.com/'); //想抓取的网址
let $ = cheerio.load(response.body) //获取网址的DOM结构
let result = $('#pane-news li a') //想抓取的部位
let news = [] //定义新闻数组
result.each((index, item) => { //循环抓取的内容
news.push($(item).text()) //循环添加到数组中
fs.writeFileSync('./news.txt', $(item).text()+'\n', {flag: 'a'}) //写入文件中
})
res.send(news) //显示在页面上
} catch (error) {
console.log(error);
}
})();
})
//打开服务器端口
app.listen(3001, () => {
console.log('http://localhost:3001')
})
提示:不会看不懂没事因为我没学node一开始也看不懂哈哈哈,直接复制粘贴。
在终端运行 http://localhost:3001/p 进行查看
图示:
要抓取的部分
成果图:
用fs模块写入txt文本:
结语:代码简单,但是没学过node应该看不懂,有注释,修改部分代码即可照葫芦画瓢抓取想要的数据。有不懂的地方可以百度或者私信。
特别提示:爬取他人网站数据好像不太好,没事尽量少爬。