查看: 396|回复: 1

[网站源码] 获取每日新闻api

[复制链接]
累计签到:35 天
连续签到:2 天

173

主题

-103

回帖

2278

积分

热心会员

名望
0
星币
548
星辰
18
好评
27
发表于 2023-11-2 22:47:15 | 显示全部楼层 |阅读模式

注册登录后全站资源免费查看下载

您需要 登录 才可以下载或查看,没有账号?立即注册

×
九月份的时候,因为每天上班时候坐电梯想看下昨天发生了啥,就寻思写个接口获取一下新闻,然后推送过来;找了好几家接口都更新速度太慢了,索性自己来了;

基本逻辑:

是抓包知乎里的一个大佬每天更新,他差不多每天凌晨更新, 我早8更新肯定木得问题;

知乎地址:https://www.zhihu.com/api/v4/columns/c_1261258401923026944/items

然后根据获取的数据进行解析:


  1. // 将HTML字符串转换为DOM对象
  2. const parser = new DOMParser();
  3. const doc = parser.parseFromString(html, 'text/html');
  4. // 选择所有的<p>元素
  5. const paragraphs = doc.querySelectorAll('p');
  6. // 遍历每个<p>元素并提取文本内容
  7. const texts = [];
  8. // 输出提取的文本内容
  9. paragraphs.forEach((p) => { const text = p.textContent.trim(); texts.push(text); });
  10. // 输出数据
  11. console.log(texts);
复制代码
根据这个解析数据写node脚本

  1. const express = require('express');
  2. const https = require('https');
  3. const cheerio = require('cheerio');

  4. const app = express();
  5. const port = 3000;

  6. app.get('/api/data', (req, res) => {
  7.   // 发起GET请求获取API数据
  8.   https.get('https://www.zhihu.com/api/v4/columns/c_1261258401923026944/items', (response) => {
  9.     let data = '';

  10.     // 接收数据块并拼接
  11.     response.on('data', (chunk) => {
  12.       data += chunk;
  13.     });

  14.     // 数据接收完毕后进行处理
  15.     response.on('end', () => {
  16.       try {
  17.         const jsonData = JSON.parse(data); // 解析返回的JSON数据
  18.         const firstItem = jsonData.data[0]; // 获取第一条数据
  19.         const content = firstItem.content; // 获取content字段

  20.         // 使用cheerio加载HTML字符串
  21.         const $ = cheerio.load(content);

  22.         // 选择所有的<p>元素
  23.         const paragraphs = $('p');

  24.         // 遍历每个<p>元素并提取非空文本内容
  25.         const texts = [];
  26.         paragraphs.each((index, element) => {
  27.           const text = $(element).text().trim();
  28.           if (text !== '') {
  29.             texts.push(text);
  30.           }
  31.         });

  32.         // 添加当前时间和返回状态
  33.         const result = {
  34.           status: response.statusCode,
  35.           timestamp: new Date().toLocaleString(),
  36.           data: texts
  37.         };

  38.         // 返回结果
  39.         res.json(result);
  40.       } catch (error) {
  41.         console.error('Error:', error.message);
  42.         res.status(500).json({ error: 'Internal Server Error' });
  43.       }
  44.     });
  45.   }).on('error', (error) => {
  46.     console.error('Error:', error.message);
  47.     res.status(500).json({ error: 'Internal Server Error' });
  48.   });
  49. });

  50. app.listen(port, () => {
  51.   console.log(`Server is running on port ${port}`);
  52. });
复制代码
后来闲着没事,写了个脚本推送给wx测试程序, 我写了定时,每天早8推给我

  1. const axios = require('axios');
  2. const cron = require('node-cron');

  3. // 配置参数
  4. const config = {
  5.   appId: 'xxxxx',
  6.   appSecret: 'xxxxx',
  7.   openId: 'xxxxxx',
  8.   templateId: 'xxxxx',
  9. };

  10. // 获取 access_token
  11. async function getAccessToken() {
  12.   const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${config.appId}&secret=${config.appSecret}`;
  13.   try {
  14.     const response = await axios.get(url);
  15.     return response.data.access_token;
  16.   } catch (error) {
  17.     console.error(error);
  18.     throw error;
  19.   }
  20. }

  21. // 调用接口获取数据
  22. async function getDate() {
  23.   const url = `接口地址`;
  24.   try {
  25.     const response = await axios.get(url);
  26.     return response.data;
  27.   } catch (error) {
  28.     console.error(error);
  29.     throw error;
  30.   }
  31. }

  32. // 发送
  33. async function sendTemplateMessage(token, config, configdate) {
  34.   const url = `https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=${token}`;

  35.   const data = {
  36.     touser: config.openId,
  37.     template_id: config.templateId,
  38.     url: 'http://new.v60s.cn',
  39.     data: {
  40.       nowDate: {
  41.         value: configdate.data[0],
  42.         color: '#57E6E2',
  43.       },
  44.       low: {
  45.         value: configdate.data[2],
  46.         color: '#7CD47D',
  47.       },
  48.       high: {
  49.         value: configdate.data[3],
  50.         color: '#CBA476',
  51.       },
  52.       loveDate: {
  53.         value: configdate.data[configdate.data.length-1],
  54.         color: '#AEC5C8',
  55.       },
  56.     },

  57.   };
  58.   try {
  59.     const response = await axios.post(url, data);
  60.     console.log('sendTemplateMessage response:', response.data);
  61.   } catch (error) {
  62.     console.error(error);
  63.     throw error;
  64.   }
  65. }

  66. // 调用发送模板消息函数
  67. async function main() {
  68.   const configdate = await getDate();
  69.   const token = await getAccessToken();
  70.   await sendTemplateMessage(token, config, configdate);
  71. }

  72. // 每天早上8点执行
  73. cron.schedule('0 8 * * *', () => {
  74.   main();
  75. });
复制代码
最/后配一个html页面;

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4.     <meta charset="UTF-8">
  5.   <title>每天一分钟,知晓天下事</title>
  6.   <style>
  7.     /* 样式可以根据需要自行定制 */
  8.     body {
  9.       font-family: Arial, sans-serif;
  10.       background-color: #f1f1f1;
  11.     }
  12.     .container {
  13.       max-width: 800px;
  14.       margin: 0 auto;
  15.       padding: 20px;
  16.       background-color: #fff;
  17.       box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  18.       border-radius: 5px;
  19.     }
  20.     h1 {
  21.       color: #333;
  22.       text-align: center;
  23.     }
  24.     .data-list {
  25.       list-style: none;
  26.       padding: 0;
  27.     }
  28.     .data-item {
  29.       margin-bottom: 10px;
  30.       padding: 10px;
  31.       background-color: #f9f9f9;
  32.       border-radius: 5px;
  33.     }
  34.     .data-item .content {
  35.       margin-bottom: 10px;
  36.     }
  37.     .data-item .content p {
  38.       margin: 0;
  39.       padding: 0;
  40.     }
  41.     .timestamp {
  42.       text-align: center;
  43.       color: #666;
  44.     }
  45.   </style>
  46. </head>
  47. <body>
  48.   <div class="container">
  49.     <h1>每天一分钟,知晓天下事</h1>
  50.     <div class="data-list" id="dataList"></div>
  51.     <p class="timestamp" id="timestamp"></p>
  52.   </div>

  53.   <script>
  54.     // 使用异步请求获取数据
  55.     fetch('http://42.123.125.40:3000/api/data')
  56.       .then(response => response.json())
  57.       .then(data => {
  58.         const dataList = document.getElementById('dataList');
  59.         const timestamp = document.getElementById('timestamp');

  60.         // 渲染数据列表
  61.         data.data.forEach(item => {
  62.           const listItem = document.createElement('div');
  63.           listItem.className = 'data-item';

  64.           const content = document.createElement('div');
  65.           content.className = 'content';
  66.           item.split('\n').forEach(paragraph => {
  67.             const p = document.createElement('p');
  68.             p.textContent = paragraph;
  69.             content.appendChild(p);
  70.           });

  71.           listItem.appendChild(content);
  72.           dataList.appendChild(listItem);
  73.         });

  74.         // 显示时间戳
  75.         timestamp.textContent = `数据最/新更新时间:${data.timestamp}`;
  76.       })
  77.       .catch(error => console.error(error));
  78.   </script>
  79. </body>
  80. </html>
复制代码





默认签名:偏爱是我家,发展靠大家! 社区反馈邮箱Mail To:service@pai.al或paijishu@outlook.com
回复

使用道具 举报

累计签到:60 天
连续签到:1 天

1

主题

219

回帖

646

积分

星空

名望
0
星币
422
星辰
0
好评
0
发表于 昨天 12:31 | 显示全部楼层
6666666666666666666666666
默认签名:偏爱是我家,发展靠大家! 社区反馈邮箱Mail To:service@pai.al或paijishu@outlook.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|偏爱技术社区-偏爱技术吧-源码-科学刀-我爱辅助-娱乐网--教开服-游戏源码

偏爱技术社区-偏爱技术吧-源码-科学刀-我爱辅助-娱乐网-游戏源码

Powered by Discuz! X3.5

GMT+8, 2024-4-28 02:25 , Processed in 0.086554 second(s), 36 queries .

快速回复 返回顶部 返回列表