【问题标题】:How to implement Apify webhooks?如何实现 Apify webhook?
【发布时间】:2019-09-10 12:53:08
【问题描述】:

需要帮助来实施 Apify webhook。完成一项任务需要一些时间。我想添加一个 Apify webhook 它将运行另一个任务但不知道如何做到这一点。

$.ajax({
  url : 'https://api.apify.com/v2/actor-tasks/XXXXXXX/runs?token=XXXXXXXX&waitForFinish=120',  
  method : 'POST',
  contentType: 'application/json',
  dataType: 'json',
  data : JSON.stringify ({
      "queries" : "Outreach link building"
  }),
  success:function(result) {
    console.log(result);
  } 
});

webhook 将调用以下任务:

$.ajax({
   url : `https://api.apify.com/v2/datasets/${datasetId}/items?format=json`,  
   method : 'GET',
   contentType: 'application/json; charset=utf-8',
   success:function(response) {
     console.log(response); // Items from dataset
   } 

 });

顺便说一句,如果我想实现所需的方式有误,请告诉我您的建议。

【问题讨论】:

  • webhook 不调用任何任务。它只是向您的端点发送运行已完成的“通知”。你需要有某种服务器来监听 webhook。
  • 明白。我可以得到一些代码示例吗?说在运行actor之后,我会将datasetId存储在我的数据库中。演员构建完成后,我希望钩子向我的应用程序的 url 发送通知。根据通知,我将更新 datasetId 的状态。
  • 通过您的服务器与 Apify 进行集成,然后与您的前端进行通信不是更好吗?
  • 是的,我会通过我的服务器来做。运行 actor 后如何知道数据集已准备就绪?
  • 从您开始运行的那一刻起,就有项目被推送到数据集。所以只需每秒轮询一次并显示更新的数据。

标签: ajax web-scraping apify


【解决方案1】:

如果您根本不想在应用程序下方使用服务器,并且想要从客户端(前端)管理所有内容,并且同步运行的 5 分钟最大延迟对您来说太短了,您可以使用轮询。您只需调用 run 端点几次,直到它返回成功状态。

但是如果你能找到waitForFinish,就这样做,然后发送第二个调用来获取数据集

success:function(result) {
    console.log(result);
   // instead of this log, you need to put your second call here and use the `result.data.defaultDatasetId` as ID of the dataset
  } 

如果您必须等待超过 300 秒,则需要使用轮询。但我真的会避免这种情况,或者不使用带有回调的 ajax,而是使用更现代的 fetch

$.ajax({
  url : 'https://api.apify.com/v2/actor-tasks/XXXXXXX/runs?token=XXXXXXXX&waitForFinish=120',  
  method : 'POST',
  contentType: 'application/json',
  dataType: 'json',
  data : JSON.stringify ({
      "queries" : "Outreach link building"
  }),
  success:function(result) {
    console.log(result);
    // Here instead of just logging, you get the run object back with its `status`. You also find an `id` there and you can periodically poll the run with this endpoint
https://apify.com/docs/api/v2#/reference/actors/run-object/get-run

  } 

【讨论】:

  • 应用程序会将信息存储在其数据库中。这里使用日志来测试结果。
  • 喜欢this?如果是,我实际上希望有更好的用户体验。我不想让用户等待看到事情发生,我想在数据集准备好时以编程方式调用它。我可以这样做吗?
  • 另外我已经编辑了我的问题,请您检查并告诉我代码是否正确?
  • 可以每隔一段时间调用数据集,更新显示的数据。
猜你喜欢
  • 2018-03-02
  • 2020-03-14
  • 2021-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-22
  • 1970-01-01
  • 2023-01-26
相关资源
最近更新 更多