【问题标题】:Access and Loop External Datasource with Apify Puppeteer Scraper使用 Apify Puppeteer Scraper 访问和循环外部数据源
【发布时间】:2020-04-18 05:10:29
【问题描述】:

Apify Puppeteer Scraper 不会在 context object 中公开 jquery。我需要访问 Puppeteer Scraper pageFunction 中的外部 JSON 数据源,然后遍历其中一个节点。如果 jquery 可用,我会这样做:

$.get(urlAPI, function(data) {
     $.each(data.feed.entry, function(index, value) {
        var url = value.URL;

【问题讨论】:

    标签: puppeteer apify


    【解决方案1】:

    由于 handlePageFunction 在 node js 上下文中运行,所以没有 jQuery。您可以使用 Apify SDK 轻松地将 jQuery 包含到 page.evaluate 函数中。

    async function pageFunction(context) {
        const { page, request, log, Apify } = context;
        await Apify.utils.puppeteer.injectJQuery(page);
        const title = await page.evaluate(() => {
            // There is jQuery include as we incleded it using injectJQuery method
            return $('title').text()
        });
        return {
            title,
        }
    }
    

    编辑:使用requestAsBrowser

    async function pageFunction(context) {
        const { page, request, log, Apify } = context;
        const response = await Apify.utils.requestAsBrowser({ url: "http://example.com" });
        const data = JSON.parse(response.body);
        return {
            data,
        }
    }
    

    【讨论】:

    • 我需要从 pageFuntion 而不是 page.evaluate 访问外部数据源、Web 服务。 $.get 会起作用吗?
    • 您不能仅在评估方法中使用 jQuery 来获取数据,因为您在浏览器上下文中。还有另一种方法可以使用 Apify.utils.requestAsBrowser({ url: "" })。这不是一种标准的方式,但它应该可以工作。
    • Apify.utils.requestAsBrowse 可能会起作用。谢谢
    【解决方案2】:

    您不需要 JQuery(如果您熟悉它,则可以)访问外部资源。

    通常,我们通过公共库(如 request 或 Apify 自己的 httpRequest)从独立参与者中提取外部数据。不幸的是,Puppeteer Scraper 不允许使用库(只能动态下载,这可能是多余的)。

    我只会使用现代的fetch 浏览器调用。它比 JQuery 的 AJAX 更好,并且不需要注入。

    async function pageFunction(context) {
        const { page, request, log, Apify } = context;
        const json = await page.evaluate(() => {
            // There is jQuery include as we incleded it using injectJQuery method
            return await fetch('http://my-json-url.com').then((resp) => resp.json())
        });
        // Process the JSON
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-29
      • 1970-01-01
      • 2020-04-04
      • 2014-09-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-13
      相关资源
      最近更新 更多