【问题标题】:How to call ajax and console.log to debugger it in apify puppeteer crawler?如何在 apify puppeteer 爬虫中调用 ajax 和 console.log 对其进行调试?
【发布时间】:2020-09-16 09:07:18
【问题描述】:

我有一个调用 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 我无法运行它 如何解决?

【问题讨论】:

  • 您能否提供更多信息,为什么您无法运行它?在 Web Scraper 中(pageFunction 在浏览器上下文中),它应该开箱即用。理想情况下,我会让一切都异步/等待,它在 Web Scraper 之外更干净,你需要在 Puppeteer 的 page.evaluate() 中运行它

标签: apify


【解决方案1】:

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

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;
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-20
    • 1970-01-01
    • 2017-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多