node爬取新型冠状病毒的疫情实时动态

2020-06-17 08:00:19易采站长站整理

const frame = await page.mainFrame();
const bodyHandle = await frame.$('html'); //获取所有的html
//frame.evaluate()在浏览器中执行函数,相当于在控制台中执行函数,返回一个Promise
const html = await frame.evaluate(body=>body.innerHTML,bodyHandle);
await bodyHandle.dispose();
browser.close();
console.log(html);
})();

用cheerio解析html:


// 使用cheerio模块装载我们得到的页面源代码,返回的是一个类似于jquery中的$对象
// 使用这个$对象就像操作jquery对象一般去操作我们获取得到的页面的源代码
var $ = cheerio.load(html);
var $menu_box = $(".statistics___1cFUQ");
console.log($menu_box.html());

用fs写入到文件中:


/* fs.wirteFile有三个参数
* 1,第一个参数是要写入的文件路径
* 2,第二个参数是要写入得内容
* 3,第三个参数是可选参数,表示要写入的文件编码格式,一般就不写,默认就行
* 4,第四个参数是个回调函数 只有一个参数error,来判断是否写入成功
*/
fs.writeFile("./coronavirus.php",$menu_box.html(),error=>{
if(error) return console.log("写入文件失败,原因是:"+error.message);
console.log('写入成功');
});

引入到网站中:

我是直接把它放在头部,局部代码如下:


<div id="header-bg">
<style type="text/css">
.title___2d1_B img {
width: 18px;
height: 18px;
cursor:pointer;
}
#novel_coronavirus {
text-align: center;
position:relative;
top:50px;
background-color:rgba(255,255,255,0.7);
}
#novel_coronavirus li {
margin: 10px;
padding:2px;
border:1px slide #000;
}
#novel_coronavirus ul li {
list-style:none;
display: inline-block;
}
.count___3GCdh p{
font-size:12px;
}
.count___3GCdh span{
font-size:20px;
}
</style>
<div id="novel_coronavirus" >
<strong><p style="font-size:23px">新型冠状病毒疫情实时动态</p></strong>
<?php require("./test/coronavirus.php");?>
</div>
</div>

服务器上运行的完整代码:

CronJob的定时参数是 秒 分钟 小时 天 月份 星期。这里我设置成了每分钟爬取一次。(我是用mstsc远程连接后运行node coronavirus.js的,这样关闭远程桌面连接后,服务器依然会每分钟爬取一次丁香医生上的新型冠状病毒的全国疫情实时动态。 


const cheerio = require('cheerio');