How to call Apify Google Search Scrapper Task Using JQuery/Ajax?

[亡魂溺海] 提交于 2019-12-20 05:42:08

问题


I am learning to use apify/google-search-scraper through their API call. The document is given here.

I am bit confused with their documentation as I am new. Especially I need the help to configure the call. It

$.ajax({
   url : '',  
   method : "POST",
   contentType: "application/json; charset=utf-8",

   data : {   

   },
   success:function(response) {
     console.log(response.data); 
   } 

 });

url: what should I write here?

data : Should I pass parameters here?

Thanks in advance.


回答1:


You need to use run task API endpoint to run it. You can use synchronous run same as asynchronous.

If you want to run the endpoint using AJAX you can use:

$.ajax({
   url : 'https://api.apify.com/v2/actor-tasks/<your task name>/runs?token=<your api token>',  
   method : 'POST',
   contentType: 'application/json; charset=utf-8',
   success:function(response) {
     console.log(response.data); // Actor run object
   } 

 });

If you need to get data from task run as well you need to wait until it finishes. Then get data from default dataset using get dataset items API endpoint. The good thing is that you can use waitForFinish param in calling run and it waits for it finishes.

const getItemsFromDataset = (datasetId) => {
    $.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
       } 

     });
}

$.ajax({
   url : 'https://api.apify.com/v2/actor-tasks/<your task name>/runs?token=<your api token>&waitForFinish=120',  
   method : 'POST',
   dataType: 'json',
   data : JSON.stringify ({
      "queries" : "query you want to"
   }),
   success:function(response) {
     console.log(response.data); // Actor run object
     getItemsFromDataset(response.data.defaultDatasetId) 
   } 

 });

You need to finish error handling in examples.

EDIT: Added queries param to override query you want to scrape.



来源:https://stackoverflow.com/questions/57848672/how-to-call-apify-google-search-scrapper-task-using-jquery-ajax

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!