当前位置 主页 > 网站技术 > 代码类 >

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

    栏目:代码类 时间:2020-02-06 21:06

    用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 >
      <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  > 
        <strong><p >新型冠状病毒疫情实时动态</p></strong>
        <?php require("./test/coronavirus.php");?>
      </div>
    </div>
    
    

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

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

    const cheerio = require('cheerio');
    const puppeteer = require('puppeteer');
    const fs = require('fs');
    var cronJob = require('cron').CronJob;
    new cronJob('0 */1 * * * *',function(){
     update();
    },null,true);  //每分钟执行一次
    //爬取全国新型肺炎疫情实时动态并写入到指定的.php文件
    function update() {
     (async () => {
      const browser = await puppeteer.launch({args: ['--no-sandbox', '--disable-setuid-sandbox']});
      const page = await browser.newPage();
      await page.goto('https://ncov.dxy.cn/');
      const frame = await page.mainFrame();
      const bodyHandle = await frame.$('html');
      const html = await frame.evaluate(body=>body.innerHTML,bodyHandle);
      await bodyHandle.dispose();
      browser.close();
      var $ = cheerio.load(html);
      var $menu_box = $(".statistics___1cFUQ");
      fs.writeFile("coronavirus.php",$menu_box.html(),error=>{
       if(error) {
        console.log("写入文件失败,原因是:"+error.message);
       } else { 
        console.log('更新成功');
       }
      });
     })();
    }
    
    

    查看我的网站 

    总结

    以上所述是小编给大家介绍的node爬取新型冠状病毒的疫情实时动态,希望对大家有所帮助!