首页 > 解决方案 > 如何在 apify puppeteer 爬虫中调用 ajax 和 console.log 对其进行调试?

问题描述

我有一个网站,点击按钮时调用 ajax 加载更多数据。在这种情况下,我使用 ajax 来调用加载更多数据。分页也是如此。我的代码如下:

function callAj(page) {
    context.log.info('load page : ' + page);
    // This log can show when I run the task.
    fetch("url", {
        "headers": {
            "accept": "*/*",
            "accept-language": "vi,en-US;q=0.9,en;q=0.8",
            "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        },
        "body": "action=load_more&sid=6&cid=9&orderby=date&order=DESC&size=9&ex=false" + "&pg=" + page,
        "method": "POST"
    }).then(res => res.text())
    .then(data => { 
      if (data != '') {
          // This log can't show when I run the task.
          context.log.info('data in here can't not show: ' + data);
          $('#id').append(data); page++; callAj(page);
      }
    })
}

当我在 chrome 开发者的控制台中调用 ajax 时,它仍然运行良好。但是在 Apify 中我无法运行它如何解决?

标签: apify

解决方案


完整的代码在我的任务中:

async function pageFunction(context) {
    const $ = context.jQuery;

    function callAj(page) {
        context.log.info('load page : ' + page);
        fetch("url", {
            "headers": {
                "accept": "*/*",
                "accept-language": "vi,en-US;q=0.9,en;q=0.8",
                "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
            },
            "body": "action=load_more&sid=6&cid=9&orderby=date&order=DESC&size=9&ex=false" + "&pg=" + page,
            "method": "POST"
        }).then(res => res.text())
        .then(data => { if (data != ''){context.log.info(`data: ${data}`);$('#id').append(data); page++; callAj(page);}})
    }

    callAj(1);

    var codes = [];
    var industryContents = [];
    var results = {};
    $(".offers-details").each(function(i, e){
        if ($(e).find('.coupon-code').length > 0) {
            codes.push($(e).find('.coupon-code .btn-copy').attr('data-clipboard-text'));
            industryContents.push($(e).find('div.polyxgo_title div:last-child').text());
        }
    });
    // $('.coupon-code .btn-copy').get().forEach((e) => codes.push($(e).attr('data-clipboard-text')));
    // $(".offers-details div.polyxgo_title > div:nth-child(6)").get().forEach((e) => industryContents.push($(e).text()));
    codes.map((e, i) => {
        results[e] = industryContents[i];
    })
    context.log.info(`code: ${codes}`);
    context.log.info(`industryContent: ${industryContents}`);
    context.log.info(results);
    return results;
}

运行它后,我无法收到足够的结果。


推荐阅读