node查询金价

124 阅读1分钟

运行之前首先确保自己安装了node环境,需要安装cheerio库

npm i cheerio

然后执行代码即可

const http = require('http');
const cheerio = require('cheerio');

function fetchData(url) {
  return new Promise((resolve, reject) => {
    http.get(url, (res) => {
      let data = '';

      res.on('data', (chunk) => {
        data += chunk;
      });

      res.on('end', () => {
        resolve(data);
      });
    }).on('error', (err) => {
      reject(err);
    });
  });
}

async function fetchAllData() {
  try {
    const response1 = await fetchData('http://www.dyhjw.com/brand/zhouliufu/');
    const response2 = await fetchData('http://dyhjw.com/brand/laofengxiang/');
    const response3 = await fetchData('http://www.dyhjw.com/brand/jinzhizun/');
    const $ = cheerio.load(response1);
    // html() 和 text() 都可以
    const divContent1 = $("body > div.main.w1020.float_clear > div.inx_l.float_clear > div.desc_txt.float_clear > div.desc_tit.fr.float_clear > div:nth-child(1) > p > span > font").text();
    console.log("今日周六福金价:"+divContent1+"克");

    const $1 = cheerio.load(response1);
    // html() 和 text() 都可以
    const divContent2 = $1("body > div.main.w1020.float_clear > div.inx_l.float_clear > div.desc_txt.float_clear > div.desc_tit.fr.float_clear > div:nth-child(1) > p > span > font").text();
    console.log("今日老凤祥金价:"+divContent2+"克");

    const $2 = cheerio.load(response1);
    // html() 和 text() 都可以
    const divContent3 = $2("body > div.main.w1020.float_clear > div.inx_l.float_clear > div.desc_txt.float_clear > div.desc_tit.fr.float_clear > div:nth-child(1) > p > span > font").text();
    console.log("今日金至尊金价:"+divContent3+"克");

    // console.log(response2);
    // console.log(response3);
    // 在这里处理两个请求的结果
  } catch (error) {
    console.error('请求遇到问题:', error);
  }
}

fetchAllData();

image.png