You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js-Osmosis:如何将爬取结果传递至其他函数?

解决Osmosis爬取数据传递到外部函数的问题

我完全懂你的困扰——Osmosis的回调式写法很容易让爬取到的数据“困”在data()的回调函数里,没法在外部逻辑(比如OneSignal通知函数)里使用。核心问题是异步编程的执行顺序:当你在回调外面写代码时,回调里的逻辑还没执行,自然拿不到document['city']的值。

咱们用Promise把爬虫逻辑包装一下,就能轻松打破这个“回调牢笼”,把数据传递到任何需要的地方。下面是具体的解决方案:

1. 把Osmosis爬虫封装成Promise

Promise是处理异步操作的标准方式,我们可以把整个爬虫流程包裹在Promise中,成功爬取时resolve出需要的数据,出错时reject错误信息:

const Osmosis = require('osmosis');

function fetchTargetCity() {
  return new Promise((resolve, reject) => {
    Osmosis
      .get('你的目标网页URL') // 替换成你要爬的网页地址
      .find('你的城市选择器') // 替换成定位city元素的CSS选择器
      .data(function(document) {
        // 成功拿到city值,把它传递出去
        resolve(document['city']);
      })
      .error(function(err) {
        // 爬虫过程出错时,传递错误信息
        reject(new Error(`爬虫出错:${err}`));
      });
  });
}

2. 用async/await获取数据并调用OneSignal

有了Promise封装的爬虫函数,我们就可以用async/await(或者.then())来同步化异步流程,拿到city值后直接传给OneSignal的通知函数:

const OneSignal = require('onesignal-node');

// 封装发送OneSignal通知的逻辑
async function sendCityNotification(city) {
  // 初始化OneSignal客户端(替换成你的密钥和应用ID)
  const client = new OneSignal.Client({
    userAuthKey: '你的OneSignal用户AuthKey',
    app: {
      appAuthKey: '你的应用AuthKey',
      appId: '你的应用ID'
    }
  });

  // 构造通知内容,把爬取到的city嵌入进去
  const notification = {
    contents: {
      en: `来自${city}的最新通知!`
    },
    included_segments: ['All'] // 替换成你要发送的目标分段
  };

  try {
    const response = await client.createNotification(notification);
    console.log('通知发送成功:', response.body);
  } catch (err) {
    console.error('通知发送失败:', err);
  }
}

// 主流程:先爬数据,再发通知
async function main() {
  try {
    const city = await fetchTargetCity();
    console.log('成功爬取城市:', city);
    await sendCityNotification(city);
  } catch (err) {
    console.error('流程出错:', err);
  }
}

// 启动整个流程
main();

补充说明

如果你的爬虫需要获取多个字段(比如城市+气温+新闻标题),只需要在resolve时传递一个对象即可:

// 在fetchTargetCity的data回调里
resolve({
  city: document['city'],
  temperature: document['temp'],
  headline: document['news']
});

// 然后在main函数里
const data = await fetchTargetCity();
await sendCityNotification(data.city, data.temperature); // 按需传递字段

内容的提问来源于stack exchange,提问作者Stfnsn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 10:08:25