使用Apify Puppeteer Scraper访问和循环外部数据源

时间:2019-12-28 19:24:01

标签: puppeteer apify

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;

2 个答案:

答案 0 :(得分:0)

由于handlePageFunction在节点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,
    }
}

答案 1 :(得分:0)

您不需要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
}